@module-federation/nextjs-mf 5.2.1 → 5.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 ScriptedAlchemy LLC (Zack Jackson)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -1,487 +1,7 @@
1
1
  'use strict';
2
2
 
3
- var path = require('path');
4
- var helpers = require('./loaders/helpers');
5
- var nextPageMapLoader = require('./loaders/nextPageMapLoader');
3
+ var NextFederationPlugin = require('./NextFederationPlugin2.js');
6
4
 
7
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
8
5
 
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
- ...(this._extraOptions.skipSharingNextInternals
224
- ? {}
225
- : externalizedShares),
226
- ...this._options.shared,
227
- },
228
- }),
229
- new webpack.web.JsonpTemplatePlugin(childOutput),
230
- new LoaderTargetPlugin('web'),
231
- new LibraryPlugin(this._options.library.type),
232
- new webpack.DefinePlugin({
233
- 'process.env.REMOTES': JSON.stringify(this._options.remotes),
234
- 'process.env.CURRENT_HOST': JSON.stringify(this._options.name),
235
- }),
236
- new AddRuntimeRequirementToPromiseExternal(),
237
- ]
238
- );
239
- new RemoveRRRuntimePlugin().apply(childCompiler);
240
-
241
- childCompiler.options.module.rules.forEach((rule) => {
242
- // next-image-loader fix which adds remote's hostname to the assets url
243
- if (
244
- this._extraOptions.enableImageLoaderFix &&
245
- helpers.hasLoader(rule, 'next-image-loader')
246
- ) {
247
- helpers.injectRuleLoader(rule, {
248
- loader: path__default["default"].resolve(__dirname, './loaders/fixImageLoader.js'),
249
- });
250
- }
251
-
252
- // url-loader fix for which adds remote's hostname to the assets url
253
- if (
254
- this._extraOptions.enableUrlLoaderFix &&
255
- helpers.hasLoader(rule, 'url-loader')
256
- ) {
257
- helpers.injectRuleLoader({
258
- loader: path__default["default"].resolve(__dirname, './loaders/fixUrlLoader.js'),
259
- });
260
- }
261
- });
262
-
263
- const MiniCss = childCompiler.options.plugins.find((p) => {
264
- return p.constructor.name === 'NextMiniCssExtractPlugin';
265
- });
266
-
267
- const removePlugins = [
268
- 'NextJsRequireCacheHotReloader',
269
- 'BuildManifestPlugin',
270
- 'WellKnownErrorsPlugin',
271
- 'WebpackBuildEventsPlugin',
272
- 'HotModuleReplacementPlugin',
273
- 'NextMiniCssExtractPlugin',
274
- 'NextFederationPlugin',
275
- 'CopyFilePlugin',
276
- 'ProfilingPlugin',
277
- 'DropClientPage',
278
- 'ReactFreshWebpackPlugin',
279
- ];
280
-
281
- childCompiler.options.plugins = childCompiler.options.plugins.filter(
282
- (plugin) => !removePlugins.includes(plugin.constructor.name)
283
- );
284
-
285
- if (MiniCss) {
286
- new MiniCss.constructor({
287
- ...MiniCss.options,
288
- filename: MiniCss.options.filename.replace('.css', '-fed.css'),
289
- chunkFilename: MiniCss.options.chunkFilename.replace(
290
- '.css',
291
- '-fed.css'
292
- ),
293
- }).apply(childCompiler);
294
- }
295
-
296
- childCompiler.options.experiments.lazyCompilation = false;
297
- childCompiler.options.optimization.runtimeChunk = false;
298
- delete childCompiler.options.optimization.splitChunks;
299
- childCompiler.outputFileSystem = compiler.outputFileSystem;
300
- if (compiler.options.mode === 'development') {
301
- childCompiler.run((err, stats) => {
302
- if (err) {
303
- console.error(err);
304
- throw new Error(err);
305
- }
306
- });
307
- } else {
308
- childCompiler.runAsChild((err, stats) => {
309
- if (err) {
310
- console.error(err);
311
- throw new Error(err);
312
- }
313
- });
314
- }
315
- });
316
- }
317
- }
318
-
319
- class AddRuntimeRequirementToPromiseExternal {
320
- apply(compiler) {
321
- compiler.hooks.compilation.tap(
322
- 'AddRuntimeRequirementToPromiseExternal',
323
- (compilation) => {
324
- const RuntimeGlobals = compiler.webpack.RuntimeGlobals;
325
- // if (compilation.outputOptions.trustedTypes) {
326
- compilation.hooks.additionalModuleRuntimeRequirements.tap(
327
- 'AddRuntimeRequirementToPromiseExternal',
328
- (module, set, context) => {
329
- if (module.externalType === 'promise') {
330
- set.add(RuntimeGlobals.loadScript);
331
- set.add(RuntimeGlobals.require);
332
- }
333
- }
334
- );
335
- // }
336
- }
337
- );
338
- }
339
- }
340
-
341
- function extractUrlAndGlobal(urlAndGlobal) {
342
- const index = urlAndGlobal.indexOf('@');
343
- if (index <= 0 || index === urlAndGlobal.length - 1) {
344
- throw new Error(`Invalid request "${urlAndGlobal}"`);
345
- }
346
- return [urlAndGlobal.substring(index + 1), urlAndGlobal.substring(0, index)];
347
- }
348
-
349
- function generateRemoteTemplate(url, global) {
350
- return `promise new Promise(function (resolve, reject) {
351
- var __webpack_error__ = new Error();
352
- if (typeof ${global} !== 'undefined') return resolve();
353
- __webpack_require__.l(
354
- ${JSON.stringify(url)},
355
- function (event) {
356
- if (typeof ${global} !== 'undefined') return resolve();
357
- var errorType = event && (event.type === 'load' ? 'missing' : event.type);
358
- var realSrc = event && event.target && event.target.src;
359
- __webpack_error__.message =
360
- 'Loading script failed.\\n(' + errorType + ': ' + realSrc + ')';
361
- __webpack_error__.name = 'ScriptExternalLoadError';
362
- __webpack_error__.type = errorType;
363
- __webpack_error__.request = realSrc;
364
- reject(__webpack_error__);
365
- },
366
- ${JSON.stringify(global)},
367
- );
368
- }).then(function () {
369
- const proxy = {
370
- get: ${global}.get,
371
- init: (args) => {
372
- const handler = {
373
- get(target, prop) {
374
- if (target[prop]) {
375
- Object.values(target[prop]).forEach(function(o) {
376
- if(o.from === '_N_E') {
377
- o.loaded = true
378
- }
379
- })
380
- }
381
- return target[prop]
382
- },
383
- set(target, property, value, receiver) {
384
- if (target[property]) {
385
- return target[property]
386
- }
387
- target[property] = value
388
- return true
389
- }
390
- }
391
- try {
392
- ${global}.init(new Proxy(__webpack_require__.S.default, handler))
393
- } catch (e) {
394
-
395
- }
396
- ${global}.__initialized = true
397
- }
398
- }
399
- if (!${global}.__initialized) {
400
- proxy.init()
401
- }
402
- return proxy
403
- })`;
404
- }
405
-
406
- function createRuntimeVariables(remotes) {
407
- return Object.entries(remotes).reduce((acc, remote) => {
408
- acc[remote[0]] = remote[1].replace('promise ', '');
409
- return acc;
410
- }, {});
411
- }
412
-
413
- class NextFederationPlugin {
414
- constructor(options) {
415
- const { extraOptions, ...mainOpts } = options;
416
- this._options = mainOpts;
417
- this._extraOptions = extraOptions;
418
- if (options.remotes) {
419
- const parsedRemotes = Object.entries(options.remotes).reduce(
420
- (acc, remote) => {
421
- if (remote[1].includes('@')) {
422
- const [url, global] = extractUrlAndGlobal(remote[1]);
423
- acc[remote[0]] = generateRemoteTemplate(url, global);
424
- return acc;
425
- }
426
- acc[remote[0]] = remote[1];
427
- return acc;
428
- },
429
- {}
430
- );
431
- this._options.remotes = parsedRemotes;
432
- }
433
- if(this._options.library) {
434
- console.error('[mf] you cannot set custom library');
435
- }
436
- this._options.library = {
437
- // assign remote name to object to avoid SWC mangling top level variable
438
- type: 'window',
439
- name: this._options.name,
440
- };
441
- }
442
-
443
- apply(compiler) {
444
- const webpack = compiler.webpack;
445
- const sharedForHost = Object.entries({
446
- ...(this._options.shared || {}),
447
- ...DEFAULT_SHARE_SCOPE,
448
- }).reduce((acc, item) => {
449
- const [itemKey, shareOptions] = item;
450
-
451
- const shareKey = 'host' + (item.shareKey || itemKey);
452
- acc[shareKey] = shareOptions;
453
- if (!shareOptions.import) {
454
- acc[shareKey].import = itemKey;
455
- }
456
- if (!shareOptions.shareKey) {
457
- acc[shareKey].shareKey = itemKey;
458
- }
459
-
460
- if (DEFAULT_SHARE_SCOPE[itemKey]) {
461
- acc[shareKey].packageName = itemKey;
462
- }
463
- return acc;
464
- }, {});
465
-
466
- new webpack.container.ModuleFederationPlugin({
467
- ...this._options,
468
- exposes: {},
469
- shared: {
470
- noop: {
471
- import: 'data:text/javascript,module.exports = {};',
472
- requiredVersion: false,
473
- version: '0',
474
- },
475
- ...sharedForHost,
476
- },
477
- }).apply(compiler);
478
- new webpack.DefinePlugin({
479
- 'process.env.REMOTES': createRuntimeVariables(this._options.remotes),
480
- 'process.env.CURRENT_HOST': JSON.stringify(this._options.name),
481
- }).apply(compiler);
482
- new ChildFederation(this._options, this._extraOptions).apply(compiler);
483
- new AddRuntimeRequirementToPromiseExternal().apply(compiler);
484
- }
485
- }
486
6
 
487
7
  module.exports = NextFederationPlugin;
Binary file
@@ -1,3 +1,7 @@
1
+ const path = require('path');
2
+ const Template = require('webpack/lib/Template');
3
+ const RuntimeGlobals = require('webpack/lib/RuntimeGlobals');
4
+
1
5
  /**
2
6
  * This loader was specially created for tunning next-image-loader result
3
7
  * see https://github.com/vercel/next.js/blob/canary/packages/next/build/webpack/loaders/next-image-loader.js
@@ -12,14 +16,44 @@
12
16
  *
13
17
  * @type {(this: import("webpack").LoaderContext<{}>, content: string) => string>}
14
18
  */
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')";
19
+ async function fixImageLoader(remaining) {
20
+ this.cacheable(true);
21
+ const isServer = this._compiler.options.name !== 'client';
22
+ const result = await this.importModule(
23
+ `${this.resourcePath}.webpack[javascript/auto]` + `!=!${remaining}`
24
+ );
25
+ const content = result.default || result;
26
+
27
+ const computedAssetPrefix = isServer
28
+ ? ` \'\'`
29
+ : `(${RuntimeGlobals.publicPath} && ${RuntimeGlobals.publicPath}.indexOf('://') > 0 ? new URL(${RuntimeGlobals.publicPath}).origin : \'\')`;
21
30
 
22
- return content.replace('"src":', `"src":${currentHostnameCode}+`);
31
+ const constructedObject = Object.entries(content).reduce(
32
+ (acc, [key, value]) => {
33
+ if (key === 'src') {
34
+ if (value && value.indexOf('://') < 0) {
35
+ value = path.join(value);
36
+ }
37
+ acc.push(
38
+ `${key}: computedAssetsPrefixReference + ${JSON.stringify(value)}`
39
+ );
40
+ return acc;
41
+ }
42
+ acc.push(`${key}: ${JSON.stringify(value)}`);
43
+ return acc;
44
+ },
45
+ []
46
+ );
47
+ const updated = Template.asString([
48
+ "let computedAssetsPrefixReference = '';",
49
+ 'try {',
50
+ Template.indent(`computedAssetsPrefixReference = ${computedAssetPrefix};`),
51
+ '} catch (e) {}',
52
+ 'export default {',
53
+ Template.indent(constructedObject.join(',\n')),
54
+ '}',
55
+ ]);
56
+ return updated;
23
57
  }
24
58
 
25
- module.exports = fixImageLoader;
59
+ module.exports.pitch = fixImageLoader;
@@ -33,3 +33,15 @@ module.exports.hasLoader = function hasLoader(rule, loaderName) {
33
33
  }
34
34
  return false;
35
35
  };
36
+
37
+ module.exports.toDisplayErrors = function toDisplayErrors(err) {
38
+ return err
39
+ .map((error) => {
40
+ let message = error.message;
41
+ if (error.stack) {
42
+ message += '\n' + error.stack;
43
+ }
44
+ return message;
45
+ })
46
+ .join('\n');
47
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "public": true,
3
3
  "name": "@module-federation/nextjs-mf",
4
- "version": "5.2.1",
4
+ "version": "5.2.2",
5
5
  "description": "Module Federation helper for NextJS",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",