├── .gitignore ├── Readme.md ├── package.json └── src ├── NodeAsyncHttpRuntime ├── CommonJsChunkLoadingPlugin.js ├── LoadFileChunkLoadingRuntimeModule.js └── index.js ├── NodeModuleFederation └── index.js ├── index.js └── templates └── rpcLoad.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | package-lock.json 3 | yalc.lock 4 | yarn.lock 5 | .yalc 6 | dist -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # About 2 | Library is a set of webpack plugins which gives support of Module Federation into NodeJS. 3 | 4 | Usage example with NextJS https://github.com/telenko/node-mf-example 5 | 6 | Here is also my [article](https://mangolik931.medium.com/how-i-implemented-module-federation-in-nodejs-and-did-something-wrong-724642c26da5) about this library. 7 | 8 | # Purpose of creating 9 | Release of [Webpack Module Federation](https://webpack.js.org/concepts/module-federation/) really have made a shift in modern architecture of web applications. But what about NodeJS and such frameworks like [Next](https://nextjs.org/)? What about SSR? I see for now a gap in webpack, so pure ModuleFederation plugin can not be used inside NodeJS environment. Muliple examples of NextJS+MF here https://github.com/module-federation/module-federation-examples with NextJS using only client-side rendering or not using remote deployed build at all. 10 | 11 | # What can I propose 12 | I have implemented 2 plugins for webpack: 13 | 1) **NodeAsyncHttpRuntime** - Plugin which should be used on a remote side to build remote scripts for NodeJS. But the main key of plugin is resolution of modules - it is done via http requests, so NodeJS can dynamically resolve child modules, load them and perform. 14 | 2) **NodeModuleFederation** - Plugin is wrapper around origin WebpackModuleFederation plugin and adds NodeJS specific resolution of remote modules (same thing: resolution is done via http requests) 15 | 16 | # Getting started 17 | ### 1) On remote library: 18 | 19 | 1.1) Install package (remote can be either pure JS application or NodeJS application - doesn't matter) 20 | ``` 21 | npm i --save-dev @telenko/node-mf 22 | ``` 23 | 24 | 1.2. Customize webpack configuration, so it should now build 2 targets: for web (if you want legacy browser build) and for node (webpack for now doesn't support universal targets) 25 | 26 | 1.3) For node build add **NodeAsyncHttpRuntime** plugin and set webpack's 'target' flag to false 27 | 28 | ```js 29 | //pseudocode 30 | module.exports = [ 31 | { 32 | target: "web", 33 | ...webOptionsWebpack 34 | }, 35 | { 36 | target: false, 37 | plugins: [ 38 | new NodeAsyncHttpRuntime() //this is instead of target to make it work 39 | ], 40 | ...nodeOptionsWebpack 41 | } 42 | ]; 43 | ``` 44 | 45 | 1.4) Serve both builds 46 | 47 | Full example is here https://github.com/telenko/node-mf-example/blob/master/remoteLib/webpack.config.js 48 | 49 | ### 2) On NodeJS application: 50 | 51 | 2.1) Install library 52 | ``` 53 | npm i --save-dev @telenko/node-mf 54 | ``` 55 | 56 | 2.2) Add **NodeModuleFederation** plugin to the webpack config (api parameters schema is same) 57 | **!Note, remote script url should point to 'node' build (which should be built with NodeAsyncHttpRuntime)** 58 | 59 | ```js 60 | module.exports = { 61 | plugins: [ 62 | new NodeModuleFederation({ 63 | remotes: { 64 | someLib: "someLib@http://some-url/remoteEntry.node.js" 65 | }, 66 | shared: { 67 | lodash: { 68 | eager: true, 69 | singleton: true, 70 | requiredVersion: "1.1.2" 71 | } 72 | } 73 | }) 74 | ], 75 | ...otherWebpackOptions 76 | }; 77 | ``` 78 | 79 | ### Usage with Next.js 80 | 81 | As Next.js use an internal version of webpack, it's mandatory to use their version. To do so, use the second argument of the 2 plugins to send the "context" of the [webpack options](https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config). 82 | 83 | ```js 84 | // next.config.js 85 | module.exports = { 86 | webpack: (config, options) => { 87 | config.plugins.push( 88 | new NodeAsyncHttpRuntime({}, options) 89 | ); 90 | return config 91 | }, 92 | } 93 | ``` 94 | ```js 95 | // next.config.js 96 | module.exports = { 97 | webpack: (config, options) => { 98 | config.plugins.push( 99 | new NodeModuleFederation({ 100 | remotes: { 101 | someLib: "someLib@http://some-url/remoteEntry.node.js" 102 | }, 103 | shared: { 104 | lodash: { 105 | eager: true, 106 | singleton: true, 107 | requiredVersion: "1.1.2" 108 | } 109 | } 110 | }, options) 111 | ); 112 | return config 113 | }, 114 | } 115 | ``` 116 | 117 | Full example of setuping NextJS with SSR here https://github.com/telenko/node-mf-example/blob/master/host/next.config.js 118 | 119 | ### Usage with runtime uris 120 | 121 | If you do not know the real uri during the build step, you can use a promise which will be executed at runtime. 122 | 123 | Here is an example based on [telenko/node-mf-example](https://github.com/telenko/node-mf-example) to have an url according to the dev or CDN host. On the CDN, the assets are stored in a path according to the remote app name. The environment variable `CDN_URL` is only known on the production server so we set an alternative for the development env. 124 | 125 | ```js 126 | // host 127 | module.exports = { 128 | webpack: (config, options) => { 129 | // [...] 130 | if (isServer) { 131 | // Set the public path of the remote as auto 132 | mfConf.remotes.remoteLib = "remoteLib@auto"; 133 | // Parse the remote uri and return a promise template string with the runtime data 134 | mfConf.getRemoteUri = function (remoteUri) { 135 | const remoteName = remoteUri.split("@")[0]; 136 | return `new Promise(r => { 137 | const uri = "${process.env.CDN_URL ? `${process.env.CDN_URL}/${remoteName}` : 'http://localhost:3002'}"; 138 | r("${remoteName}@${uri}/node/remoteEntry.js"); 139 | })` 140 | } 141 | } 142 | // [...] 143 | } 144 | }; 145 | ``` 146 | 147 | ```js 148 | // remoteLib 149 | const getConfig = (target) => ({ 150 | plugins: [ 151 | ...(target === "web" 152 | ? [ 153 | new HtmlWebpackPlugin({ 154 | template: "./public/index.html" 155 | }) 156 | ] 157 | : [ 158 | new NodeAsyncHttpRuntime({ 159 | getBaseUri = function () { 160 | // Return a promise template string with the runtime data 161 | return `new Promise(r => { 162 | const uri = "${process.env.CDN_URL ? `${process.env.CDN_URL}/remoteLib` : 'http://localhost:3002'}"; 163 | r("${uri}/${target}/"); 164 | })` 165 | } 166 | }) 167 | ] 168 | ) 169 | ] 170 | }); 171 | ``` 172 | 173 | # Risks 174 | ## Aren't 2 build makes build-time 2 times longer? 175 | Yes, if we speak about NextJS and SSR - we need both builds: for web and for node, and we have to start entire build separately without sharing built chunks. That will increase build time 2 times. 176 | ## Security 177 | Since NodeJS out of the box doesn't support remote scripts execution (like in browser we can add **script** tag) it looks like a hack calling http request then 'eval'-ing it. I'm not sure if it is safe to add remote script execution on server side, but it is the only one possible way to make it on server. 178 | 179 | # Roadmap 180 | 1) https support 181 | 2) Next.js support for NodeAsyncHttpRuntime plugin -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@telenko/node-mf", 3 | "version": "0.0.7", 4 | "description": "Module Federation plugin support for NodeJS", 5 | "main": "src/index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "peerDependencies": { 10 | "webpack": "^5.38.1" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/telenko/node-mf.git" 15 | }, 16 | "keywords": [ 17 | "Module", 18 | "federation", 19 | "nodejs", 20 | "node", 21 | "next", 22 | "webpack" 23 | ], 24 | "author": "Andrii Telenko", 25 | "license": "MIT", 26 | "bugs": { 27 | "url": "https://github.com/telenko/node-mf/issues" 28 | }, 29 | "homepage": "https://github.com/telenko/node-mf#readme" 30 | } 31 | -------------------------------------------------------------------------------- /src/NodeAsyncHttpRuntime/CommonJsChunkLoadingPlugin.js: -------------------------------------------------------------------------------- 1 | const RuntimeGlobals = require("webpack/lib/RuntimeGlobals"); 2 | const StartupChunkDependenciesPlugin = require("webpack/lib/runtime/StartupChunkDependenciesPlugin"); 3 | const ChunkLoadingRuntimeModule = require("./LoadFileChunkLoadingRuntimeModule"); 4 | 5 | class CommonJsChunkLoadingPlugin { 6 | constructor(options, context) { 7 | this.options = options || {}; 8 | this._asyncChunkLoading = this.options.asyncChunkLoading; 9 | this.context = context || {}; 10 | } 11 | 12 | /** 13 | * Apply the plugin 14 | * @param {Compiler} compiler the compiler instance 15 | * @returns {void} 16 | */ 17 | apply(compiler) { 18 | const chunkLoadingValue = this._asyncChunkLoading 19 | ? "async-node" 20 | : "require"; 21 | new StartupChunkDependenciesPlugin({ 22 | chunkLoading: chunkLoadingValue, 23 | asyncChunkLoading: this._asyncChunkLoading, 24 | }).apply(compiler); 25 | compiler.hooks.thisCompilation.tap( 26 | "CommonJsChunkLoadingPlugin", 27 | (compilation) => { 28 | // Always enabled 29 | const isEnabledForChunk = () => true; 30 | const onceForChunkSet = new WeakSet(); 31 | const handler = (chunk, set) => { 32 | if (onceForChunkSet.has(chunk)) return; 33 | onceForChunkSet.add(chunk); 34 | if (!isEnabledForChunk(chunk)) return; 35 | set.add(RuntimeGlobals.moduleFactoriesAddOnly); 36 | set.add(RuntimeGlobals.hasOwnProperty); 37 | compilation.addRuntimeModule( 38 | chunk, 39 | new ChunkLoadingRuntimeModule(set, this.options, this.context) 40 | ); 41 | }; 42 | 43 | compilation.hooks.runtimeRequirementInTree 44 | .for(RuntimeGlobals.ensureChunkHandlers) 45 | .tap("CommonJsChunkLoadingPlugin", handler); 46 | compilation.hooks.runtimeRequirementInTree 47 | .for(RuntimeGlobals.hmrDownloadUpdateHandlers) 48 | .tap("CommonJsChunkLoadingPlugin", handler); 49 | compilation.hooks.runtimeRequirementInTree 50 | .for(RuntimeGlobals.hmrDownloadManifest) 51 | .tap("CommonJsChunkLoadingPlugin", handler); 52 | compilation.hooks.runtimeRequirementInTree 53 | .for(RuntimeGlobals.baseURI) 54 | .tap("CommonJsChunkLoadingPlugin", handler); 55 | compilation.hooks.runtimeRequirementInTree 56 | .for(RuntimeGlobals.externalInstallChunk) 57 | .tap("CommonJsChunkLoadingPlugin", handler); 58 | compilation.hooks.runtimeRequirementInTree 59 | .for(RuntimeGlobals.onChunksLoaded) 60 | .tap("CommonJsChunkLoadingPlugin", handler); 61 | 62 | compilation.hooks.runtimeRequirementInTree 63 | .for(RuntimeGlobals.ensureChunkHandlers) 64 | .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { 65 | if (!isEnabledForChunk(chunk)) return; 66 | set.add(RuntimeGlobals.getChunkScriptFilename); 67 | }); 68 | compilation.hooks.runtimeRequirementInTree 69 | .for(RuntimeGlobals.hmrDownloadUpdateHandlers) 70 | .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { 71 | if (!isEnabledForChunk(chunk)) return; 72 | set.add(RuntimeGlobals.getChunkUpdateScriptFilename); 73 | set.add(RuntimeGlobals.moduleCache); 74 | set.add(RuntimeGlobals.hmrModuleData); 75 | set.add(RuntimeGlobals.moduleFactoriesAddOnly); 76 | }); 77 | compilation.hooks.runtimeRequirementInTree 78 | .for(RuntimeGlobals.hmrDownloadManifest) 79 | .tap("CommonJsChunkLoadingPlugin", (chunk, set) => { 80 | if (!isEnabledForChunk(chunk)) return; 81 | set.add(RuntimeGlobals.getUpdateManifestFilename); 82 | }); 83 | } 84 | ); 85 | } 86 | } 87 | 88 | module.exports = CommonJsChunkLoadingPlugin; 89 | -------------------------------------------------------------------------------- /src/NodeAsyncHttpRuntime/LoadFileChunkLoadingRuntimeModule.js: -------------------------------------------------------------------------------- 1 | /* 2 | MIT License http://www.opensource.org/licenses/mit-license.php 3 | */ 4 | 5 | "use strict"; 6 | 7 | const RuntimeGlobals = require("webpack/lib/RuntimeGlobals"); 8 | const RuntimeModule = require("webpack/lib/RuntimeModule"); 9 | const Template = require("webpack/lib/Template"); 10 | const { getInitialChunkIds } = require("webpack/lib/javascript/StartupHelpers"); 11 | const compileBooleanMatcher = require("webpack/lib/util/compileBooleanMatcher"); 12 | const { getUndoPath } = require("webpack/lib/util/identifier"); 13 | 14 | const rpcLoadTemplate = require("../templates/rpcLoad"); 15 | 16 | class ReadFileChunkLoadingRuntimeModule extends RuntimeModule { 17 | constructor(runtimeRequirements, options, context) { 18 | super("readFile chunk loading", RuntimeModule.STAGE_ATTACH); 19 | this.runtimeRequirements = runtimeRequirements; 20 | this.options = options; 21 | this.context = context; 22 | } 23 | 24 | /** 25 | * @returns {string} runtime code 26 | */ 27 | generate() { 28 | const { chunkGraph, chunk } = this; 29 | const { baseURI, getBaseUri } = this.options; 30 | const { webpack } = this.context; 31 | const { runtimeTemplate } = this.compilation; 32 | const fn = RuntimeGlobals.ensureChunkHandlers; 33 | const withBaseURI = this.runtimeRequirements.has(RuntimeGlobals.baseURI); 34 | const withExternalInstallChunk = this.runtimeRequirements.has( 35 | RuntimeGlobals.externalInstallChunk 36 | ); 37 | const withOnChunkLoad = this.runtimeRequirements.has( 38 | RuntimeGlobals.onChunksLoaded 39 | ); 40 | const withLoading = this.runtimeRequirements.has( 41 | RuntimeGlobals.ensureChunkHandlers 42 | ); 43 | const withHmr = this.runtimeRequirements.has( 44 | RuntimeGlobals.hmrDownloadUpdateHandlers 45 | ); 46 | const withHmrManifest = this.runtimeRequirements.has( 47 | RuntimeGlobals.hmrDownloadManifest 48 | ); 49 | const conditionMap = chunkGraph.getChunkConditionMap( 50 | chunk, 51 | webpack?.javascript.JavascriptModulesPlugin.chunkHasJs || 52 | require("webpack/lib/javascript/JavascriptModulesPlugin").chunkHasJs 53 | ); 54 | const hasJsMatcher = compileBooleanMatcher(conditionMap); 55 | const initialChunkIds = getInitialChunkIds(chunk, chunkGraph); 56 | 57 | const outputName = this.compilation.getPath( 58 | ( 59 | webpack?.javascript.JavascriptModulesPlugin.getChunkFilenameTemplate || 60 | require("webpack/lib/javascript/JavascriptModulesPlugin") 61 | .getChunkFilenameTemplate 62 | )(chunk, this.compilation.outputOptions), 63 | { 64 | chunk, 65 | contentHashType: "javascript", 66 | } 67 | ); 68 | const rootOutputDir = getUndoPath( 69 | outputName, 70 | this.compilation.outputOptions.path, 71 | false 72 | ); 73 | 74 | return Template.asString([ 75 | withBaseURI 76 | ? Template.asString([ 77 | `${RuntimeGlobals.baseURI} = require("url").pathToFileURL(${ 78 | rootOutputDir 79 | ? `__dirname + ${JSON.stringify("/" + rootOutputDir)}` 80 | : "__filename" 81 | });`, 82 | ]) 83 | : "// no baseURI", 84 | "", 85 | "// object to store loaded chunks", 86 | '// "0" means "already loaded", Promise means loading', 87 | "var installedChunks = {", 88 | Template.indent( 89 | Array.from(initialChunkIds, (id) => `${JSON.stringify(id)}: 0`).join( 90 | ",\n" 91 | ) 92 | ), 93 | "};", 94 | "", 95 | withOnChunkLoad 96 | ? `${ 97 | RuntimeGlobals.onChunksLoaded 98 | }.readFileVm = ${runtimeTemplate.returningFunction( 99 | "installedChunks[chunkId] === 0", 100 | "chunkId" 101 | )};` 102 | : "// no on chunks loaded", 103 | "", 104 | withLoading || withExternalInstallChunk 105 | ? `var installChunk = ${runtimeTemplate.basicFunction("chunk", [ 106 | "var moreModules = chunk.modules, chunkIds = chunk.ids, runtime = chunk.runtime;", 107 | "for(var moduleId in moreModules) {", 108 | Template.indent([ 109 | `if(${RuntimeGlobals.hasOwnProperty}(moreModules, moduleId)) {`, 110 | Template.indent([ 111 | `${RuntimeGlobals.moduleFactories}[moduleId] = moreModules[moduleId];`, 112 | ]), 113 | "}", 114 | ]), 115 | "}", 116 | `if(runtime) runtime(__webpack_require__);`, 117 | "for(var i = 0; i < chunkIds.length; i++) {", 118 | Template.indent([ 119 | "if(installedChunks[chunkIds[i]]) {", 120 | Template.indent(["installedChunks[chunkIds[i]][0]();"]), 121 | "}", 122 | "installedChunks[chunkIds[i]] = 0;", 123 | ]), 124 | "}", 125 | withOnChunkLoad ? `${RuntimeGlobals.onChunksLoaded}();` : "", 126 | ])};` 127 | : "// no chunk install function needed", 128 | "", 129 | withLoading 130 | ? Template.asString([ 131 | "// ReadFile + VM.run chunk loading for javascript", 132 | `${fn}.readFileVm = function(chunkId, promises) {`, 133 | hasJsMatcher !== false 134 | ? Template.indent([ 135 | "", 136 | "var installedChunkData = installedChunks[chunkId];", 137 | 'if(installedChunkData !== 0) { // 0 means "already installed".', 138 | Template.indent([ 139 | '// array of [resolve, reject, promise] means "currently loading"', 140 | "if(installedChunkData) {", 141 | Template.indent(["promises.push(installedChunkData[2]);"]), 142 | "} else {", 143 | Template.indent([ 144 | hasJsMatcher === true 145 | ? "if(true) { // all chunks have JS" 146 | : `if(${hasJsMatcher("chunkId")}) {`, 147 | Template.indent([ 148 | "// load the chunk and return promise to it", 149 | "var promise = new Promise(async function(resolve, reject) {", 150 | Template.indent([ 151 | "installedChunkData = installedChunks[chunkId] = [resolve, reject];", 152 | `var filename = require('path').join(__dirname, ${JSON.stringify( 153 | rootOutputDir 154 | )} + ${ 155 | RuntimeGlobals.getChunkScriptFilename 156 | }(chunkId));`, 157 | rpcLoadTemplate, 158 | `rpcLoad(${ 159 | getBaseUri 160 | ? `await ${getBaseUri(baseURI)}` 161 | : `"${baseURI}"` 162 | }, ${ 163 | RuntimeGlobals.getChunkScriptFilename 164 | }(chunkId), function(err, content) {`, 165 | Template.indent([ 166 | "if(err) return reject(err);", 167 | "var chunk = {};", 168 | "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + 169 | "(chunk, require, require('path').dirname(filename), filename);", 170 | "installChunk(chunk);", 171 | ]), 172 | "});", 173 | ]), 174 | "});", 175 | "promises.push(installedChunkData[2] = promise);", 176 | ]), 177 | "} else installedChunks[chunkId] = 0;", 178 | ]), 179 | "}", 180 | ]), 181 | "}", 182 | ]) 183 | : Template.indent(["installedChunks[chunkId] = 0;"]), 184 | "};", 185 | ]) 186 | : "// no chunk loading", 187 | "", 188 | withExternalInstallChunk 189 | ? Template.asString([ 190 | "module.exports = __webpack_require__;", 191 | `${RuntimeGlobals.externalInstallChunk} = installChunk;`, 192 | ]) 193 | : "// no external install chunk", 194 | "", 195 | withHmr 196 | ? Template.asString([ 197 | "function loadUpdateChunk(chunkId, updatedModulesList) {", 198 | Template.indent([ 199 | "return new Promise(async function(resolve, reject) {", 200 | Template.indent([ 201 | `var filename = require('path').join(__dirname, ${JSON.stringify( 202 | rootOutputDir 203 | )} + ${RuntimeGlobals.getChunkUpdateScriptFilename}(chunkId));`, 204 | rpcLoadTemplate, 205 | `rpcLoad(${ 206 | promiseBaseURI ? `await ${promiseBaseURI}` : `"${baseURI}"` 207 | }, ${ 208 | RuntimeGlobals.getChunkUpdateScriptFilename 209 | }(chunkId), function(err, content) {`, 210 | Template.indent([ 211 | "if(err) return reject(err);", 212 | "var update = {};", 213 | "require('vm').runInThisContext('(function(exports, require, __dirname, __filename) {' + content + '\\n})', filename)" + 214 | "(update, require, require('path').dirname(filename), filename);", 215 | "var updatedModules = update.modules;", 216 | "var runtime = update.runtime;", 217 | "for(var moduleId in updatedModules) {", 218 | Template.indent([ 219 | `if(${RuntimeGlobals.hasOwnProperty}(updatedModules, moduleId)) {`, 220 | Template.indent([ 221 | `currentUpdate[moduleId] = updatedModules[moduleId];`, 222 | "if(updatedModulesList) updatedModulesList.push(moduleId);", 223 | ]), 224 | "}", 225 | ]), 226 | "}", 227 | "if(runtime) currentUpdateRuntime.push(runtime);", 228 | "resolve();", 229 | ]), 230 | "});", 231 | ]), 232 | "});", 233 | ]), 234 | "}", 235 | "", 236 | Template.getFunctionContent( 237 | require("../hmr/JavascriptHotModuleReplacement.runtime.js") 238 | ) 239 | .replace(/\$key\$/g, "readFileVm") 240 | .replace(/\$installedChunks\$/g, "installedChunks") 241 | .replace(/\$loadUpdateChunk\$/g, "loadUpdateChunk") 242 | .replace(/\$moduleCache\$/g, RuntimeGlobals.moduleCache) 243 | .replace(/\$moduleFactories\$/g, RuntimeGlobals.moduleFactories) 244 | .replace( 245 | /\$ensureChunkHandlers\$/g, 246 | RuntimeGlobals.ensureChunkHandlers 247 | ) 248 | .replace(/\$hasOwnProperty\$/g, RuntimeGlobals.hasOwnProperty) 249 | .replace(/\$hmrModuleData\$/g, RuntimeGlobals.hmrModuleData) 250 | .replace( 251 | /\$hmrDownloadUpdateHandlers\$/g, 252 | RuntimeGlobals.hmrDownloadUpdateHandlers 253 | ) 254 | .replace( 255 | /\$hmrInvalidateModuleHandlers\$/g, 256 | RuntimeGlobals.hmrInvalidateModuleHandlers 257 | ), 258 | ]) 259 | : "// no HMR", 260 | "", 261 | withHmrManifest 262 | ? Template.asString([ 263 | `${RuntimeGlobals.hmrDownloadManifest} = function() {`, 264 | Template.indent([ 265 | "return new Promise(function(resolve, reject) {", 266 | Template.indent([ 267 | `var filename = require('path').join(__dirname, ${JSON.stringify( 268 | rootOutputDir 269 | )} + ${RuntimeGlobals.getUpdateManifestFilename}());`, 270 | //TODO manifest support 271 | "require('fs').readFile(filename, 'utf-8', function(err, content) {", 272 | Template.indent([ 273 | "if(err) {", 274 | Template.indent([ 275 | 'if(err.code === "ENOENT") return resolve();', 276 | "return reject(err);", 277 | ]), 278 | "}", 279 | "try { resolve(JSON.parse(content)); }", 280 | "catch(e) { reject(e); }", 281 | ]), 282 | "});", 283 | ]), 284 | "});", 285 | ]), 286 | "}", 287 | ]) 288 | : "// no HMR manifest", 289 | ]); 290 | } 291 | } 292 | 293 | module.exports = ReadFileChunkLoadingRuntimeModule; 294 | -------------------------------------------------------------------------------- /src/NodeAsyncHttpRuntime/index.js: -------------------------------------------------------------------------------- 1 | const CommonJsChunkLoadingPlugin = require("./CommonJsChunkLoadingPlugin"); 2 | 3 | class NodeAsyncHttpRuntime { 4 | constructor(options, context) { 5 | this.options = options || {}; 6 | this.context = context || {}; 7 | } 8 | 9 | apply(compiler) { 10 | if (compiler.options.target) { 11 | console.warn( 12 | `target should be set to false while using NodeAsyncHttpRuntime plugin, actual target: ${compiler.options.target}` 13 | ); 14 | } 15 | 16 | // When used with Next.js, context is needed to use Next.js webpack 17 | const { webpack } = this.context; 18 | 19 | // This will enable CommonJsChunkFormatPlugin 20 | compiler.options.output.chunkFormat = "commonjs"; 21 | // This will force async chunk loading 22 | compiler.options.output.chunkLoading = "async-node"; 23 | // Disable default config 24 | compiler.options.output.enabledChunkLoadingTypes = false; 25 | 26 | new (webpack?.node.NodeEnvironmentPlugin || 27 | require("webpack/lib/node/NodeEnvironmentPlugin"))({ 28 | infrastructureLogging: compiler.options.infrastructureLogging, 29 | }).apply(compiler); 30 | new (webpack?.node.NodeTargetPlugin || 31 | require("webpack/lib/node/NodeTargetPlugin"))().apply(compiler); 32 | new CommonJsChunkLoadingPlugin( 33 | { 34 | asyncChunkLoading: true, 35 | baseURI: compiler.options.output.publicPath, 36 | getBaseUri: this.options.getBaseUri, 37 | }, 38 | this.context 39 | ).apply(compiler); 40 | } 41 | } 42 | 43 | module.exports = NodeAsyncHttpRuntime; 44 | -------------------------------------------------------------------------------- /src/NodeModuleFederation/index.js: -------------------------------------------------------------------------------- 1 | const rpcLoadTemplate = require("../templates/rpcLoad"); 2 | 3 | const rpcPerformTemplate = ` 4 | ${rpcLoadTemplate} 5 | function rpcPerform(remoteUrl) { 6 | const scriptUrl = remoteUrl.split("@")[1]; 7 | const moduleName = remoteUrl.split("@")[0]; 8 | return new Promise(function (resolve, reject) { 9 | rpcLoad(scriptUrl, function(error, scriptContent) { 10 | if (error) { reject(error); } 11 | //TODO using vm?? 12 | const remote = eval(scriptContent + '\\n try{' + moduleName + '}catch(e) { null; };'); 13 | if (!remote) { 14 | reject("remote library " + moduleName + " is not found at " + scriptUrl); 15 | } else if (remote instanceof Promise) { 16 | return remote; 17 | } else { 18 | resolve(remote); 19 | } 20 | }); 21 | }); 22 | } 23 | `; 24 | 25 | const rpcProcessTemplate = (mfConfig) => ` 26 | function rpcProcess(remote) { 27 | return {get:(request)=> remote.get(request),init:(arg)=>{try {return remote.init({ 28 | ...arg, 29 | ${Object.keys(mfConfig.shared || {}) 30 | .filter( 31 | (item) => 32 | mfConfig.shared[item].singleton && 33 | mfConfig.shared[item].requiredVersion 34 | ) 35 | .map(function (item) { 36 | return `"${item}": { 37 | ["${mfConfig.shared[item].requiredVersion}"]: { 38 | get: () => Promise.resolve().then(() => () => require("${item}")) 39 | } 40 | }`; 41 | }) 42 | .join(",")} 43 | })} catch(e){console.log('remote container already initialized')}}} 44 | } 45 | `; 46 | 47 | function buildRemotes(mfConf, getRemoteUri) { 48 | const builtinsTemplate = ` 49 | ${rpcPerformTemplate} 50 | ${rpcProcessTemplate(mfConf)} 51 | `; 52 | return Object.entries(mfConf.remotes || {}).reduce((acc, [name, config]) => { 53 | acc[name] = { 54 | external: `external (async function() { 55 | ${builtinsTemplate} 56 | return rpcPerform(${ 57 | getRemoteUri 58 | ? `await ${getRemoteUri(config)}` 59 | : `"${config}"` 60 | }).then(rpcProcess).catch((err) => { console.error(err); }) 61 | }())`, 62 | }; 63 | return acc; 64 | }, {}); 65 | } 66 | 67 | class NodeModuleFederation { 68 | constructor(options, context) { 69 | this.options = options || {}; 70 | this.context = context || {}; 71 | } 72 | 73 | apply(compiler) { 74 | const { getRemoteUri, ...options } = this.options; 75 | // When used with Next.js, context is needed to use Next.js webpack 76 | const { webpack } = this.context; 77 | 78 | new (webpack?.container.ModuleFederationPlugin || 79 | require("webpack/lib/container/ModuleFederationPlugin"))({ 80 | ...options, 81 | remotes: buildRemotes(options, getRemoteUri), 82 | }).apply(compiler); 83 | } 84 | } 85 | 86 | module.exports = NodeModuleFederation; 87 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | const NodeAsyncHttpRuntime = require("./NodeAsyncHttpRuntime"); 2 | const NodeModuleFederation = require("./NodeModuleFederation"); 3 | 4 | module.exports = { 5 | NodeAsyncHttpRuntime, 6 | NodeModuleFederation, 7 | }; 8 | -------------------------------------------------------------------------------- /src/templates/rpcLoad.js: -------------------------------------------------------------------------------- 1 | /** 2 | * rpcLoad(baseURI, fileName, cb) 3 | * rpcLoad(scriptUrl, cb) 4 | */ 5 | module.exports = ` 6 | function rpcLoad() { 7 | var url; 8 | var cb = arguments[arguments.length - 1]; 9 | if (typeof cb !== "function") { 10 | throw new Error("last argument should be a function"); 11 | } 12 | if (arguments.length === 2) { 13 | url = arguments[0]; 14 | } else if (arguments.length === 3) { 15 | url = new URL(arguments[1], arguments[0]).toString(); 16 | } else { 17 | throw new Error("invalid number of arguments"); 18 | } 19 | //TODO https support 20 | let request = (url.startsWith('https') ? require('https') : require('http')).get(url, function(resp) { 21 | if (resp.statusCode === 200) { 22 | let rawData = ''; 23 | resp.setEncoding('utf8'); 24 | resp.on('data', chunk => { rawData += chunk; }); 25 | resp.on('end', () => { 26 | cb(null, rawData); 27 | }); 28 | } else { 29 | cb(resp); 30 | } 31 | }); 32 | request.on('error', error => cb(error)); 33 | } 34 | `; 35 | --------------------------------------------------------------------------------