Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Proposal: Remote as an Object #7

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,9 @@ const GenerateModuleMap = require("./src/GenerateModuleMap");
const GenerateRemoteMap = require("./src/GenerateRemoteMap");
const GenerateRemoteUrlMap = require("./src/GenerateRemoteUrlMap");
const AddRuntimeRequirementsToExternal = require("./src/AddRuntimeRequirementsToExternal");
const HandleRemoteObject = require("./src/HandleRemoteObject");


class ExtendedModuleFederationPlugin extends ModuleFederationPlugin {
class ModuleFederationEnhancedPlugin extends ModuleFederationPlugin {
constructor(options) {
if (!options.exposes) {
options.exposes = {};
Expand All @@ -21,6 +21,8 @@ class ExtendedModuleFederationPlugin extends ModuleFederationPlugin {
...GenerateRemoteUrlMap(options),
};

options.remotes = HandleRemoteObject(options.remotes);

super(options);
this.options = options;
}
Expand All @@ -30,4 +32,4 @@ class ExtendedModuleFederationPlugin extends ModuleFederationPlugin {
new AddRuntimeRequirementsToExternal().apply(compiler)
}
}
module.exports = ExtendedModuleFederationPlugin;
module.exports = ModuleFederationEnhancedPlugin;
77 changes: 56 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@

## Idea

Webpack Federation can do quite a lot, but orchestrating it can sometimes be a little messy or complex with its given api. The idea is to offer some additonal lifecycles directly on webpack interfaces to allow for pluggability and a more standardized ecosystem


Webpack Federation can do quite a lot, but orchestrating it can sometimes be a little messy or complex with its given api. The idea is to offer some additonal lifecycles directly on webpack interfaces to allow for pluggability and a more standardized ecosystem

# Remotes

Expand All @@ -18,7 +16,7 @@ new ModuleFederationPlugin({
},
(importValue) => {
if(window.remoteOverrides['app1']) {
// if an override exists, change the script that will be injected.
// if an override exists, change the script that will be injected.
return window.remoteOverrides['app1'] // --> otherRemote@http://otherUrl
} else {
return importValue // do nothing
Expand Down Expand Up @@ -46,45 +44,82 @@ new ModuleFederationPlugin({
```

## Middleware

`promise new Promise` is handy, but it would be great if one could compose a series of middlewares into the promise chain in a standard manner.
This would be useful for

- controling versions/overrides at runtime
- injecting env variables before webpack connects the containers together
- doing some series of actions during the initial import() for a remote that only happens once - prior to a remote being injected
- additional security or auth gates without having to write wrapper code around your exposed modules.
- additional security or auth gates without having to write wrapper code around your exposed modules.

## onBeforeGet
The lifecycle of federation is as follows.
1) inject remote (happens once)
2) init() remote (happens once)
3) get() exposed module (happens for every import)

The lifecycle of federation is as follows.

1. inject remote (happens once)
2. init() remote (happens once)
3. get() exposed module (happens for every import)

After middleware has been run, and the remote container injected into the application, and has initialized.
After middleware has been run, and the remote container injected into the application, and has initialized.

Sometimes i might want to do something before calling the underlaying get() of a container. perhaps re-route the module request, or set up distributed logging automatically before import() resolves and starts executing.
Sometimes i might want to do something before calling the underlaying get() of a container. perhaps re-route the module request, or set up distributed logging automatically before import() resolves and starts executing.

onBeforeGet is basically middleware but for the module import itself instead of container injection

### Remote as an Object

Initially intended to handle the async default usage, but proves a better way of hadling remote URL based on envs or whatever.

| Prop | Description |
| ------- | ------------------------------------------------------------------------------------------------- |
| async | if it must be wrapped aroung with `promise new Promise` |
| name | the name of the remote, compiled out as the name before the `@` |
| url | the url of the remoteEntry for of the remote, compiled out as the url after the `@ ` |
| onError | optional function to be called on the async if the remote is offline or had any exception loading |


The `async` prop, embed the Promise Based approach as in the [Webpack docs](https://webpack.js.org/concepts/module-federation/), turning the values passed as an objet to the `promise new Promise(resolve => {` that provides an outofbox handling of offline remotes.
#### Usage

```js
remotes: {
app1: "[email protected]/remoteEntry.js",
app2: {
name: "app2",
url: isProd ? urlProd : urlDev
},
app3: {
async: true,
name: "app3",
url: "http://coolAppRunningOnCloud.com.br/remoteEntry.js",
},
app2: {
name: "app2",
url: process.env.FINAL_REMOTE_ENTRY
},
}
```

### Custom Maps

#### Extended to remoteEntry:
| Prop | Description |
| --------- | --------------------------------------------------- |
| moduleMap | list of all available modules from a single remote. |
| remoteMap | list of all remotes available for consumption |
| remoteUrlMap | list of all remotes URL to initilize |

| Prop | Description |
| ------------ | --------------------------------------------------- |
| moduleMap | list of all available modules from a single remote. |
| remoteMap | list of all remotes available for consumption |
| remoteUrlMap | list of all remotes URL to initilize |

#### Usage

```js
const ModuleFederationEnhacedPlugin = require("@module-federation/ModuleFederationEnhacedPlugin");
const ModuleFederationEnhancedPlugin = require("@module-federation/ModuleFederationEnhancedPlugin");

module.export = {
//... rest of your config
plugins: [
new ModuleFederationEnhacedPlugin({
new ModuleFederationEnhancedPlugin({
name: "myApp",
library: { type: "var", name: "app2" },
filename: "remoteEntry.js",
Expand Down Expand Up @@ -114,10 +149,10 @@ import remoteMap from "myApp/remoteMap";
import remoteUrlMap from "myApp/remoteUrlMap";
```


#### Chunk Map

| Prop | Description |
| --------- | --------------------------------------------------- |
| Prop | Description |
| ------------- | ------------------------------------------------------------- |
| chunkMap.json | list of all chunkNames and create a json file on dist folder. |

# Got ideas? Open a issue
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@module-federation/ModuleFederationEnhacedPlugin",
"name": "@module-federation/ModuleFederationEnhancedPlugin",
"version": "1.0.0",
"main": "ModuleFederationEnhacedPlugin.js",
"main": "ModuleFederationEnhancedPlugin.js",
"license": "MIT",
"scripts": {
"prettier": "prettier --write \"**/*.{js,json,md,ts,tsx}\""
Expand All @@ -15,7 +15,7 @@
},
"repository": {
"type": "git",
"url": ".../ModuleFederationEnhacedPlugin.git"
"url": ".../ModuleFederationEnhancedPlugin.git"
},
"dependencies": {
"find-package-json": "^1.0.0"
Expand Down
2 changes: 1 addition & 1 deletion src/GenerateChunkMap.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ const GenerateChunkMap = (compiler) => {
);
};

module.exports = { GenerateChunkMap };
module.exports = GenerateChunkMap;
9 changes: 8 additions & 1 deletion src/GenerateRemoteUrlMap.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
const validateRemoteType = (remoteName, options) => {
const remote = options.remotes[remoteName];
return typeof remote === "string"
? { [remoteName]: remote.split("@")[1] }
: { [remote.name]: remote.url };
};

const GenerateRemoteUrlMap = (options) => {
if (options.remotes) {
return {
"./remoteUrlMap": `data:application/json,${JSON.stringify(
Object.keys(options.remotes).map((remoteName) => {
return { [remoteName]: options.remotes[remoteName].split("@")[1] };
return validateRemoteType(remoteName, options);
})
)}`,
};
Expand Down
58 changes: 58 additions & 0 deletions src/HandleRemoteObject.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
const defaultOnError = () => {
const module = {
get: () => () => {},
init: () => () => {},
};
resolve(module);
};

const dynamicRemote = (remote) => {
return `(resolve) => {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should use webpack require.l for script loading here. i opened a PR adding webpack runtime requirements to promise based remotes

Copy link
Member

@ScriptedAlchemy ScriptedAlchemy Aug 1, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should so this instead

 new Promise(function(resolve, reject) {
                       var __webpack_error__ = new Error();
                       if (typeof window.${
                         containerWithAtSyntax[0]
                       } !== 'undefined') return resolve();
                       var containerUrl = ${containerWithAtSyntax[1]} ? 
                       '${containerWithAtSyntax[1]}' : remoteConfig.entry
                       __webpack_require__.l(
                         containerUrl,
                         function(event) {
                           if (typeof window.${
                             containerWithAtSyntax[0]
                           } !== 'undefined') return resolve();
                           var errorType = event && (event.type === 'load' ? 'missing' : event.type);
                           var realSrc = event && event.target && event.target.src;
                           __webpack_error__.message =
                             'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';
                           __webpack_error__.name = 'ScriptExternalLoadError';
                           __webpack_error__.type = errorType;
                           __webpack_error__.request = realSrc;
                           reject(__webpack_error__);
                         },
                         '${containerWithAtSyntax[0]}',
                       );
                     })
                  ]).then(function(){
                    res(window.${containerWithAtSyntax[0]})
                  });

const script = document.createElement("script");
script.src = "${remote.url}";
script.onload = () => {
const module = {
get: (request) => window["${remote.name}"].get(request),
init: (arg) => {
try {
return window["${remote.name}"].init(arg);
} catch (e) {
console.log("Problem loading remote ${remote.name}", e);
}
},
};
resolve(module);
};
script.onerror = ${
remote.onError ? remote.onError.toString() : defaultOnError.toString()
}
document.head.appendChild(script);
}`;
};

const handleAsyncRemote = (remote) => {
return `promise new Promise(${dynamicRemote(remote).toString()})`;
};

const mountFinalRemoteValue = (remote) => {
if (remote.async) {
return handleAsyncRemote(remote);
} else {
//Any other implementation of remote as an object goes here
}

return remote.name + "@" + remote.url;
};

const HandleRemoteObject = (remotes) => {
const _newRemotes = {};
Object.keys(remotes)?.forEach((remoteName) => {
const remote = remotes[remoteName];
_newRemotes[remoteName] =
typeof remote === "string" ? remote : mountFinalRemoteValue(remote);
});

return _newRemotes;
};

module.exports = HandleRemoteObject;