@module-federation/nextjs-mf 2.3.1 → 5.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,477 @@
1
+ 'use strict';
2
+
3
+ var path = require('path');
4
+ var helpers = require('./loaders/helpers');
5
+ var nextPageMapLoader = require('./loaders/nextPageMapLoader');
6
+
7
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
+
9
+ var path__default = /*#__PURE__*/_interopDefaultLegacy(path);
10
+
11
+ const CHILD_PLUGIN_NAME = 'ChildFederationPlugin';
12
+
13
+ /** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ExternalsType} ExternalsType */
14
+ /** @typedef {import("../../declarations/plugins/container/ModuleFederationPlugin").ModuleFederationPluginOptions} ModuleFederationPluginOptions */
15
+
16
+ /** @typedef {import("webpack").Shared} Shared */
17
+ /** @typedef {import("webpack").Compiler} Compiler */
18
+
19
+ class ModuleFederationPlugin {
20
+ /**
21
+ * @param {ModuleFederationPluginOptions} options options
22
+ */
23
+ constructor(options) {
24
+ this._options = options;
25
+ }
26
+
27
+ /**
28
+ * Apply the plugin
29
+ * @param {Compiler} compiler the compiler instance
30
+ * @returns {void}
31
+ */
32
+ apply(compiler) {
33
+ const { _options: options } = this;
34
+ const webpack = compiler.webpack;
35
+ const { ContainerPlugin, ContainerReferencePlugin } = webpack.container;
36
+ const { SharePlugin } = webpack.sharing;
37
+ const library = options.library || { type: 'var', name: options.name };
38
+ const remoteType =
39
+ options.remoteType ||
40
+ (options.library && /** @type {ExternalsType} */ options.library.type) ||
41
+ 'script';
42
+ if (
43
+ library &&
44
+ !compiler.options.output.enabledLibraryTypes.includes(library.type)
45
+ ) {
46
+ compiler.options.output.enabledLibraryTypes.push(library.type);
47
+ }
48
+
49
+ if (
50
+ options.exposes &&
51
+ (Array.isArray(options.exposes)
52
+ ? options.exposes.length > 0
53
+ : Object.keys(options.exposes).length > 0)
54
+ ) {
55
+ new ContainerPlugin({
56
+ name: options.name,
57
+ library,
58
+ filename: options.filename,
59
+ runtime: options.runtime,
60
+ exposes: options.exposes,
61
+ }).apply(compiler);
62
+ }
63
+ if (
64
+ options.remotes &&
65
+ (Array.isArray(options.remotes)
66
+ ? options.remotes.length > 0
67
+ : Object.keys(options.remotes).length > 0)
68
+ ) {
69
+ new ContainerReferencePlugin({
70
+ remoteType,
71
+ remotes: options.remotes,
72
+ }).apply(compiler);
73
+ }
74
+ if (options.shared) {
75
+ new SharePlugin({
76
+ shared: options.shared,
77
+ shareScope: options.shareScope,
78
+ }).apply(compiler);
79
+ }
80
+ }
81
+ }
82
+
83
+ class RemoveRRRuntimePlugin {
84
+ /**
85
+ * Apply the plugin
86
+ * @param {Compiler} compiler the compiler instance
87
+ * @returns {void}
88
+ */
89
+ apply(compiler) {
90
+ const webpack = compiler.webpack;
91
+
92
+ compiler.hooks.thisCompilation.tap(
93
+ 'RemoveRRRuntimePlugin',
94
+ (compilation) => {
95
+ compilation.hooks.processAssets.tap(
96
+ {
97
+ name: 'RemoveRRRuntimePlugin',
98
+ state: compilation.constructor.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE,
99
+ },
100
+ (assets) => {
101
+ Object.keys(assets).forEach((filename) => {
102
+ if (filename.endsWith('.js') || filename.endsWith('.mjs')) {
103
+ const asset = compilation.getAsset(filename);
104
+ const newSource = asset.source
105
+ .source()
106
+ .replace(/RefreshHelpers/g, 'NoExist');
107
+ const updatedAsset = new webpack.sources.RawSource(newSource);
108
+
109
+ if (asset) {
110
+ compilation.updateAsset(filename, updatedAsset);
111
+ } else {
112
+ compilation.emitAsset(filename, updatedAsset);
113
+ }
114
+ }
115
+ });
116
+ }
117
+ );
118
+ }
119
+ );
120
+ }
121
+ }
122
+
123
+ const DEFAULT_SHARE_SCOPE = {
124
+ react: {
125
+ singleton: true,
126
+ requiredVersion: false,
127
+ },
128
+ 'react/jsx-runtime': {
129
+ singleton: true,
130
+ requiredVersion: false,
131
+ },
132
+ 'react-dom': {
133
+ singleton: true,
134
+ requiredVersion: false,
135
+ },
136
+ 'next/dynamic': {
137
+ requiredVersion: false,
138
+ singleton: true,
139
+ },
140
+ 'styled-jsx': {
141
+ requiredVersion: false,
142
+ singleton: true,
143
+ },
144
+ 'next/link': {
145
+ requiredVersion: false,
146
+ singleton: true,
147
+ },
148
+ 'next/router': {
149
+ requiredVersion: false,
150
+ singleton: true,
151
+ },
152
+ 'next/script': {
153
+ requiredVersion: false,
154
+ singleton: true,
155
+ },
156
+ 'next/head': {
157
+ requiredVersion: false,
158
+ singleton: true,
159
+ },
160
+ };
161
+
162
+ class ChildFederation {
163
+ constructor(options, extraOptions = {}) {
164
+ this._options = options;
165
+ this._extraOptions = extraOptions;
166
+ }
167
+
168
+ apply(compiler) {
169
+ const webpack = compiler.webpack;
170
+ webpack.EntryPlugin;
171
+ const LibraryPlugin = webpack.library.EnableLibraryPlugin;
172
+ webpack.container.ModuleFederationPlugin;
173
+ webpack.container.ContainerPlugin;
174
+ const LoaderTargetPlugin = webpack.LoaderTargetPlugin;
175
+ const library = compiler.options.output.library;
176
+
177
+ compiler.hooks.thisCompilation.tap(CHILD_PLUGIN_NAME, (compilation) => {
178
+ const buildName = this._options.name;
179
+ const childOutput = {
180
+ ...compiler.options.output,
181
+ publicPath: 'auto',
182
+ chunkLoadingGlobal: buildName + 'chunkLoader',
183
+ uniqueName: buildName,
184
+ library: {
185
+ name: buildName,
186
+ type: library.type,
187
+ },
188
+ chunkFilename: compiler.options.output.chunkFilename.replace(
189
+ '.js',
190
+ '-fed.js'
191
+ ),
192
+ filename: compiler.options.output.chunkFilename.replace(
193
+ '.js',
194
+ '-fed.js'
195
+ ),
196
+ };
197
+ const externalizedShares = Object.entries(DEFAULT_SHARE_SCOPE).reduce(
198
+ (acc, item) => {
199
+ const [key, value] = item;
200
+ acc[key] = { ...value, import: false };
201
+ if (key === 'react/jsx-runtime') {
202
+ delete acc[key].import;
203
+ }
204
+ return acc;
205
+ },
206
+ {}
207
+ );
208
+ const childCompiler = compilation.createChildCompiler(
209
+ CHILD_PLUGIN_NAME,
210
+ childOutput,
211
+ [
212
+ new ModuleFederationPlugin({
213
+ // library: {type: 'var', name: buildName},
214
+ ...this._options,
215
+ exposes: {
216
+ ...this._options.exposes,
217
+ ...(this._extraOptions.exposePages
218
+ ? nextPageMapLoader.exposeNextjsPages(compiler.options.context)
219
+ : {}),
220
+ },
221
+ runtime: false,
222
+ shared: {
223
+ ...externalizedShares,
224
+ ...this._options.shared,
225
+ },
226
+ }),
227
+ new webpack.web.JsonpTemplatePlugin(childOutput),
228
+ new LoaderTargetPlugin('web'),
229
+ new LibraryPlugin('var'),
230
+ new webpack.DefinePlugin({
231
+ 'process.env.REMOTES': JSON.stringify(this._options.remotes),
232
+ 'process.env.CURRENT_HOST': JSON.stringify(this._options.name),
233
+ }),
234
+ new AddRuntimeRequirementToPromiseExternal(),
235
+ ]
236
+ );
237
+ new RemoveRRRuntimePlugin().apply(childCompiler);
238
+
239
+ childCompiler.options.module.rules.forEach((rule) => {
240
+ // next-image-loader fix which adds remote's hostname to the assets url
241
+ if (
242
+ this._extraOptions.enableImageLoaderFix &&
243
+ helpers.hasLoader(rule, 'next-image-loader')
244
+ ) {
245
+ helpers.injectRuleLoader(rule, {
246
+ loader: path__default["default"].resolve(__dirname, './loaders/fixImageLoader.js'),
247
+ });
248
+ }
249
+
250
+ // url-loader fix for which adds remote's hostname to the assets url
251
+ if (
252
+ this._extraOptions.enableUrlLoaderFix &&
253
+ helpers.hasLoader(rule, 'url-loader')
254
+ ) {
255
+ helpers.injectRuleLoader({
256
+ loader: path__default["default"].resolve(__dirname, './loaders/fixUrlLoader.js'),
257
+ });
258
+ }
259
+ });
260
+
261
+ const MiniCss = childCompiler.options.plugins.find((p) => {
262
+ return p.constructor.name === 'NextMiniCssExtractPlugin';
263
+ });
264
+
265
+ const removePlugins = [
266
+ 'NextJsRequireCacheHotReloader',
267
+ 'BuildManifestPlugin',
268
+ 'WellKnownErrorsPlugin',
269
+ 'WebpackBuildEventsPlugin',
270
+ 'HotModuleReplacementPlugin',
271
+ 'NextMiniCssExtractPlugin',
272
+ 'NextFederationPlugin',
273
+ 'CopyFilePlugin',
274
+ 'ProfilingPlugin',
275
+ 'DropClientPage',
276
+ 'ReactFreshWebpackPlugin',
277
+ ];
278
+
279
+ childCompiler.options.plugins = childCompiler.options.plugins.filter(
280
+ (plugin) => !removePlugins.includes(plugin.constructor.name)
281
+ );
282
+
283
+ if (MiniCss) {
284
+ new MiniCss.constructor({
285
+ ...MiniCss.options,
286
+ filename: MiniCss.options.filename.replace('.css', '-fed.css'),
287
+ chunkFilename: MiniCss.options.chunkFilename.replace(
288
+ '.css',
289
+ '-fed.css'
290
+ ),
291
+ }).apply(childCompiler);
292
+ }
293
+
294
+ childCompiler.options.experiments.lazyCompilation = false;
295
+ childCompiler.options.optimization.runtimeChunk = false;
296
+ delete childCompiler.options.optimization.splitChunks;
297
+ childCompiler.outputFileSystem = compiler.outputFileSystem;
298
+ if (compiler.options.mode === 'development') {
299
+ childCompiler.run((err, stats) => {
300
+ if (err) {
301
+ console.error(err);
302
+ throw new Error(err);
303
+ }
304
+ });
305
+ } else {
306
+ childCompiler.runAsChild((err, stats) => {
307
+ if (err) {
308
+ console.error(err);
309
+ throw new Error(err);
310
+ }
311
+ });
312
+ }
313
+ });
314
+ }
315
+ }
316
+
317
+ class AddRuntimeRequirementToPromiseExternal {
318
+ apply(compiler) {
319
+ compiler.hooks.compilation.tap(
320
+ 'AddRuntimeRequirementToPromiseExternal',
321
+ (compilation) => {
322
+ const RuntimeGlobals = compiler.webpack.RuntimeGlobals;
323
+ // if (compilation.outputOptions.trustedTypes) {
324
+ compilation.hooks.additionalModuleRuntimeRequirements.tap(
325
+ 'AddRuntimeRequirementToPromiseExternal',
326
+ (module, set, context) => {
327
+ if (module.externalType === 'promise') {
328
+ set.add(RuntimeGlobals.loadScript);
329
+ set.add(RuntimeGlobals.require);
330
+ }
331
+ }
332
+ );
333
+ // }
334
+ }
335
+ );
336
+ }
337
+ }
338
+
339
+ function extractUrlAndGlobal(urlAndGlobal) {
340
+ const index = urlAndGlobal.indexOf('@');
341
+ if (index <= 0 || index === urlAndGlobal.length - 1) {
342
+ throw new Error(`Invalid request "${urlAndGlobal}"`);
343
+ }
344
+ return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)];
345
+ }
346
+
347
+ function generateRemoteTemplate(url, global) {
348
+ return `promise new Promise(function (resolve, reject) {
349
+ var __webpack_error__ = new Error();
350
+ if (typeof ${global} !== 'undefined') return resolve();
351
+ __webpack_require__.l(
352
+ ${JSON.stringify(url)},
353
+ function (event) {
354
+ if (typeof ${global} !== 'undefined') return resolve();
355
+ var errorType = event && (event.type === 'load' ? 'missing' : event.type);
356
+ var realSrc = event && event.target && event.target.src;
357
+ __webpack_error__.message =
358
+ 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';
359
+ __webpack_error__.name = 'ScriptExternalLoadError';
360
+ __webpack_error__.type = errorType;
361
+ __webpack_error__.request = realSrc;
362
+ reject(__webpack_error__);
363
+ },
364
+ ${JSON.stringify(global)},
365
+ );
366
+ }).then(function () {
367
+ const proxy = {
368
+ get: ${global}.get,
369
+ init: (args) => {
370
+ const handler = {
371
+ get(target, prop) {
372
+ if (target[prop]) {
373
+ Object.values(target[prop]).forEach(function(o) {
374
+ if(o.from === '_N_E') {
375
+ o.loaded = true
376
+ }
377
+ })
378
+ }
379
+ return target[prop]
380
+ },
381
+ set(target, property, value, receiver) {
382
+ if (target[property]) {
383
+ return target[property]
384
+ }
385
+ target[property] = value
386
+ return true
387
+ }
388
+ }
389
+ try {
390
+ ${global}.init(new Proxy(__webpack_require__.S.default, handler))
391
+ } catch (e) {
392
+
393
+ }
394
+ ${global}.__initialized = true
395
+ }
396
+ }
397
+ if (!${global}.__initialized) {
398
+ proxy.init()
399
+ }
400
+ return proxy
401
+ })`;
402
+ }
403
+
404
+ function createRuntimeVariables(remotes) {
405
+ return Object.entries(remotes).reduce((acc, remote) => {
406
+ acc[remote[0]] = remote[1].replace('promise ', '');
407
+ return acc;
408
+ }, {});
409
+ }
410
+
411
+ class NextFederationPlugin {
412
+ constructor(options) {
413
+ const { extraOptions, ...mainOpts } = options;
414
+ this._options = mainOpts;
415
+ this._extraOptions = extraOptions;
416
+ if (options.remotes) {
417
+ const parsedRemotes = Object.entries(options.remotes).reduce(
418
+ (acc, remote) => {
419
+ if (remote[1].includes('@')) {
420
+ const [url, global] = extractUrlAndGlobal(remote[1]);
421
+ acc[remote[0]] = generateRemoteTemplate(url, global);
422
+ return acc;
423
+ }
424
+ acc[remote[0]] = remote[1];
425
+ return acc;
426
+ },
427
+ {}
428
+ );
429
+ this._options.remotes = parsedRemotes;
430
+ }
431
+ }
432
+
433
+ apply(compiler) {
434
+ const webpack = compiler.webpack;
435
+ const sharedForHost = Object.entries({
436
+ ...(this._options.shared || {}),
437
+ ...DEFAULT_SHARE_SCOPE,
438
+ }).reduce((acc, item) => {
439
+ const [itemKey, shareOptions] = item;
440
+
441
+ const shareKey = 'host' + (item.shareKey || itemKey);
442
+ acc[shareKey] = shareOptions;
443
+ if (!shareOptions.import) {
444
+ acc[shareKey].import = itemKey;
445
+ }
446
+ if (!shareOptions.shareKey) {
447
+ acc[shareKey].shareKey = itemKey;
448
+ }
449
+
450
+ if (DEFAULT_SHARE_SCOPE[itemKey]) {
451
+ acc[shareKey].packageName = itemKey;
452
+ }
453
+ return acc;
454
+ }, {});
455
+
456
+ new webpack.container.ModuleFederationPlugin({
457
+ ...this._options,
458
+ exposes: {},
459
+ shared: {
460
+ noop: {
461
+ import: 'data:text/javascript,module.exports = {};',
462
+ requiredVersion: false,
463
+ version: '0',
464
+ },
465
+ ...sharedForHost,
466
+ },
467
+ }).apply(compiler);
468
+ new webpack.DefinePlugin({
469
+ 'process.env.REMOTES': createRuntimeVariables(this._options.remotes),
470
+ 'process.env.CURRENT_HOST': JSON.stringify(this._options.name),
471
+ }).apply(compiler);
472
+ new ChildFederation(this._options, this._extraOptions).apply(compiler);
473
+ new AddRuntimeRequirementToPromiseExternal().apply(compiler);
474
+ }
475
+ }
476
+
477
+ module.exports = NextFederationPlugin;
@@ -0,0 +1,16 @@
1
+ // if(process.browser && (typeof __webpack_share_scopes__ === "undefined" || !__webpack_share_scopes__.default)) {
2
+ // __webpack_init_sharing__('default');
3
+ // }
4
+ require('react');
5
+ require('react-dom');
6
+ require('next/link');
7
+ require('next/router');
8
+ require('next/head');
9
+ require('next/script');
10
+ require('next/dynamic');
11
+ require('styled-jsx');
12
+ if (process.env.NODE_ENV === 'development') {
13
+ require('react/jsx-dev-runtime');
14
+ }
15
+
16
+ module.exports = {};
package/lib/index.js ADDED
@@ -0,0 +1,3 @@
1
+ const NextFederationPlugin = require('./NextFederationPlugin');
2
+
3
+ module.exports = NextFederationPlugin;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * This loader was specially created for tunning next-image-loader result
3
+ * see https://github.com/vercel/next.js/blob/canary/packages/next/build/webpack/loaders/next-image-loader.js
4
+ * It takes regular string
5
+ * `export default {"src":"/_next/static/media/ssl.e3019f0e.svg","height":20,"width":20};`
6
+ * And injects PUBLIC_PATH to it from webpack
7
+ * `export default {"src":__webpack_require__.p+"/static/media/ssl.e3019f0e.svg","height":20,"width":20};`
8
+ *
9
+ *
10
+ * __webpack_require__.p - is a global variable in webpack container which contains publicPath
11
+ * For example: http://localhost:3000/_next
12
+ *
13
+ * @type {(this: import("webpack").LoaderContext<{}>, content: string) => string>}
14
+ */
15
+ function fixImageLoader(content) {
16
+ // replace(/(.+\:\/\/[^\/]+){0,1}\/.*/i, '$1')
17
+ // this regexp will extract the hostname from publicPath
18
+ // http://localhost:3000/_next/... -> http://localhost:3000
19
+ const currentHostnameCode =
20
+ "__webpack_require__.p.replace(/(.+\\:\\/\\/[^\\/]+){0,1}\\/.*/i, '$1')";
21
+
22
+ return content.replace('"src":', `"src":${currentHostnameCode}+`);
23
+ }
24
+
25
+ module.exports = fixImageLoader;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * This loader was specially created for tunning url-loader result
3
+ *
4
+ * And injects PUBLIC_PATH to it from webpack runtime
5
+ * `export default __webpack_require__.p + "/static/media/ssl.e3019f0e.svg"`
6
+ *
7
+ * __webpack_require__.p - is a global variable in webpack container which contains publicPath
8
+ * For example: http://localhost:3000/_next
9
+ *
10
+ * @type {(this: import("webpack").LoaderContext<{}>, content: string) => string>}
11
+ */
12
+ function fixUrlLoader(content) {
13
+ // replace(/(.+\:\/\/[^\/]+){0,1}\/.*/i, '$1')
14
+ // this regexp will extract the hostname from publicPath
15
+ // http://localhost:3000/_next/... -> http://localhost:3000
16
+ const currentHostnameCode =
17
+ "__webpack_require__.p.replace(/(.+\\:\\/\\/[^\\/]+){0,1}\\/.*/i, '$1')";
18
+
19
+ return content.replace(
20
+ 'export default "/',
21
+ `export default ${currentHostnameCode}+"/`
22
+ );
23
+ }
24
+
25
+ module.exports = fixUrlLoader;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Inject a loader into the current module rule.
3
+ * This function mutates `rule` argument!
4
+ */
5
+ module.exports.injectRuleLoader = function injectRuleLoader(rule, loader) {
6
+ if (rule.loader) {
7
+ rule.use = [loader, { loader: rule.loader, options: rule.options }];
8
+ delete rule.loader;
9
+ delete rule.options;
10
+ } else if (rule.use) {
11
+ rule.use = [loader, ...rule.use];
12
+ }
13
+ };
14
+
15
+ /**
16
+ * Check that current module rule has a loader with the provided name.
17
+ */
18
+ module.exports.hasLoader = function hasLoader(rule, loaderName) {
19
+ if (rule.loader === loaderName) {
20
+ return true;
21
+ } else if (rule.use) {
22
+ for (let i = 0; i < rule.use.length; i++) {
23
+ const loader = rule.use[i];
24
+ // check exact name, eg "url-loader" or its path "node_modules/url-loader/dist/cjs.js"
25
+ if (
26
+ loader.loader === loaderName ||
27
+ loader.loader.includes(`/${loaderName}/`)
28
+ ) {
29
+ return true;
30
+ }
31
+ }
32
+ }
33
+ return false;
34
+ };