@module-federation/node 0.0.0-feat-node-support-1702696727086 → 0.0.0-next-20231219093413

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.
Files changed (99) hide show
  1. package/.babelrc +10 -0
  2. package/.eslintrc.json +47 -0
  3. package/CHANGELOG.md +1352 -0
  4. package/LICENSE +21 -0
  5. package/README.md +192 -0
  6. package/assets/banner.png +0 -0
  7. package/dist/jest.config.js +19 -0
  8. package/dist/jest.config.js.map +1 -0
  9. package/dist/package.json +62 -0
  10. package/dist/src/filesystem/stratagies.d.ts +11 -0
  11. package/{src → dist/src}/filesystem/stratagies.js +11 -31
  12. package/dist/src/filesystem/stratagies.js.map +1 -0
  13. package/{src → dist/src}/index.d.ts +2 -0
  14. package/{src → dist/src}/index.js +5 -1
  15. package/dist/src/index.js.map +1 -0
  16. package/dist/src/plugins/AutomaticPublicPathPlugin.js.map +1 -0
  17. package/dist/src/plugins/ChunkCorrelationPlugin.js +442 -0
  18. package/dist/src/plugins/ChunkCorrelationPlugin.js.map +1 -0
  19. package/dist/src/plugins/CommonJsChunkLoadingPlugin.js.map +1 -0
  20. package/{src → dist/src}/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js +13 -0
  21. package/dist/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js.map +1 -0
  22. package/dist/src/plugins/NodeContainerPlugin.d.ts +57 -0
  23. package/dist/src/plugins/NodeContainerPlugin.js +105 -0
  24. package/dist/src/plugins/NodeContainerPlugin.js.map +1 -0
  25. package/{src → dist/src}/plugins/NodeFederationPlugin.d.ts +20 -0
  26. package/dist/src/plugins/NodeFederationPlugin.js +127 -0
  27. package/dist/src/plugins/NodeFederationPlugin.js.map +1 -0
  28. package/dist/src/plugins/RemotePublicPathRuntimeModule.js.map +1 -0
  29. package/{src → dist/src}/plugins/StreamingTargetPlugin.js.map +1 -1
  30. package/{src → dist/src}/plugins/UniversalFederationPlugin.d.ts +0 -1
  31. package/{src → dist/src}/plugins/UniversalFederationPlugin.js +3 -3
  32. package/dist/src/plugins/UniversalFederationPlugin.js.map +1 -0
  33. package/{src → dist/src}/plugins/webpackChunkUtilities.js +5 -1
  34. package/dist/src/plugins/webpackChunkUtilities.js.map +1 -0
  35. package/dist/src/types/index.js.map +1 -0
  36. package/dist/src/utils/flush-chunks.js.map +1 -0
  37. package/dist/src/utils/hot-reload.js.map +1 -0
  38. package/dist/src/utils/index.js.map +1 -0
  39. package/global.d.ts +27 -0
  40. package/jest.config.js +14 -16
  41. package/package.json +17 -23
  42. package/project.json +58 -0
  43. package/src/filesystem/stratagies.ts +131 -0
  44. package/src/index.ts +7 -0
  45. package/src/plugins/AutomaticPublicPathPlugin.ts +48 -0
  46. package/src/plugins/ChunkCorrelationPlugin.js +474 -307
  47. package/src/plugins/CommonJsChunkLoadingPlugin.ts +168 -0
  48. package/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.ts +239 -0
  49. package/src/plugins/NodeContainerPlugin.ts +150 -0
  50. package/src/plugins/NodeFederationPlugin.ts +185 -0
  51. package/src/plugins/RemotePublicPathRuntimeModule.ts +137 -0
  52. package/src/plugins/StreamingTargetPlugin.md +88 -0
  53. package/src/plugins/StreamingTargetPlugin.ts +81 -0
  54. package/src/plugins/UniversalFederationPlugin.ts +81 -0
  55. package/src/plugins/webpackChunkUtilities.ts +383 -0
  56. package/src/types/index.ts +7 -0
  57. package/src/utils/flush-chunks.ts +182 -0
  58. package/src/utils/hot-reload.ts +169 -0
  59. package/src/utils/index.ts +2 -0
  60. package/tsconfig.json +28 -0
  61. package/tsconfig.lib.json +17 -0
  62. package/tsconfig.spec.json +9 -0
  63. package/jest.config.js.map +0 -1
  64. package/src/filesystem/stratagies.d.ts +0 -18
  65. package/src/filesystem/stratagies.js.map +0 -1
  66. package/src/index.js.map +0 -1
  67. package/src/plugins/AutomaticPublicPathPlugin.js.map +0 -1
  68. package/src/plugins/ChunkCorrelationPlugin.js.map +0 -1
  69. package/src/plugins/CommonJsChunkLoadingPlugin.js.map +0 -1
  70. package/src/plugins/DynamicFilesystemChunkLoadingRuntimeModule.js.map +0 -1
  71. package/src/plugins/NodeFederationPlugin.js +0 -76
  72. package/src/plugins/NodeFederationPlugin.js.map +0 -1
  73. package/src/plugins/RemotePublicPathRuntimeModule.js.map +0 -1
  74. package/src/plugins/UniversalFederationPlugin.js.map +0 -1
  75. package/src/plugins/webpackChunkUtilities.js.map +0 -1
  76. package/src/types/index.js.map +0 -1
  77. package/src/utils/flush-chunks.js.map +0 -1
  78. package/src/utils/hot-reload.js.map +0 -1
  79. package/src/utils/index.js.map +0 -1
  80. package/{jest.config.d.ts → dist/jest.config.d.ts} +0 -0
  81. package/{src → dist/src}/plugins/AutomaticPublicPathPlugin.d.ts +0 -0
  82. package/{src → dist/src}/plugins/AutomaticPublicPathPlugin.js +0 -0
  83. package/{src → dist/src}/plugins/ChunkCorrelationPlugin.d.ts +6 -6
  84. /package/{src → dist/src}/plugins/CommonJsChunkLoadingPlugin.d.ts +0 -0
  85. /package/{src → dist/src}/plugins/CommonJsChunkLoadingPlugin.js +0 -0
  86. /package/{src → dist/src}/plugins/DynamicFilesystemChunkLoadingRuntimeModule.d.ts +0 -0
  87. /package/{src → dist/src}/plugins/RemotePublicPathRuntimeModule.d.ts +0 -0
  88. /package/{src → dist/src}/plugins/RemotePublicPathRuntimeModule.js +0 -0
  89. /package/{src → dist/src}/plugins/StreamingTargetPlugin.d.ts +0 -0
  90. /package/{src → dist/src}/plugins/StreamingTargetPlugin.js +0 -0
  91. /package/{src → dist/src}/plugins/webpackChunkUtilities.d.ts +0 -0
  92. /package/{src → dist/src}/types/index.d.ts +0 -0
  93. /package/{src → dist/src}/types/index.js +0 -0
  94. /package/{src → dist/src}/utils/flush-chunks.d.ts +0 -0
  95. /package/{src → dist/src}/utils/flush-chunks.js +0 -0
  96. /package/{src → dist/src}/utils/hot-reload.d.ts +0 -0
  97. /package/{src → dist/src}/utils/hot-reload.js +0 -0
  98. /package/{src → dist/src}/utils/index.d.ts +0 -0
  99. /package/{src → dist/src}/utils/index.js +0 -0
@@ -0,0 +1,185 @@
1
+ 'use strict';
2
+
3
+ import type { Compiler, container } from 'webpack';
4
+ import type { ModuleFederationPluginOptions } from '../types';
5
+ import { extractUrlAndGlobal } from '@module-federation/utilities';
6
+ import { ModuleInfoRuntimePlugin } from '@module-federation/enhanced';
7
+
8
+ /**
9
+ * Interface for NodeFederationOptions which extends ModuleFederationPluginOptions
10
+ * @interface
11
+ * @property {Record<string, unknown>} experiments - Optional experiments configuration
12
+ * @property {boolean} debug - Optional debug flag
13
+ */
14
+ interface NodeFederationOptions extends ModuleFederationPluginOptions {
15
+ experiments?: Record<string, unknown>;
16
+ debug?: boolean;
17
+ }
18
+
19
+ /**
20
+ * Interface for Context
21
+ * @interface
22
+ * @property {typeof container.ModuleFederationPlugin} ModuleFederationPlugin - Optional ModuleFederationPlugin
23
+ */
24
+ interface Context {
25
+ ModuleFederationPlugin?: typeof container.ModuleFederationPlugin;
26
+ }
27
+
28
+ /**
29
+ * This function iterates over all remotes and checks if they
30
+ * are internal or not. If it's an internal remote then we add it to our new object
31
+ * with a key of the name of the remote and value as internal. If it's not an internal
32
+ * remote then we check if there is a '@' in that string which likely means it is a global @ url
33
+ *
34
+ * @param {Record<string, any>} remotes - The remotes to parse.
35
+ * @returns {Record<string, string>} - The parsed remotes.
36
+ * */
37
+
38
+ export const parseRemotes = (
39
+ remotes: Record<string, any>,
40
+ ): Record<string, string> => {
41
+ if (!remotes || typeof remotes !== 'object') {
42
+ throw new Error('remotes must be an object');
43
+ }
44
+
45
+ return Object.entries(remotes).reduce(
46
+ (acc: Record<string, string>, [key, value]) => {
47
+ const isInternal = value.startsWith('internal ');
48
+ const isGlobal =
49
+ value.includes('@') &&
50
+ !['window.', 'global.', 'globalThis.', 'self.'].some((prefix) =>
51
+ value.startsWith(prefix),
52
+ );
53
+
54
+ acc[key] = isInternal || !isGlobal ? value : parseRemoteSyntax(value);
55
+
56
+ return acc;
57
+ },
58
+ {},
59
+ );
60
+ };
61
+ /**
62
+ * Parses the remote syntax and returns a formatted string if the remote includes '@' and does not start with 'window', 'global', or 'globalThis'.
63
+ * Otherwise, it returns the original remote string.
64
+ *
65
+ * @param {string} remote - The remote string to parse.
66
+ * @returns {string} - The parsed remote string or the original remote string.
67
+ * @throws {Error} - Throws an error if the remote is not a string.
68
+ */
69
+ export const parseRemoteSyntax = (remote: any): string => {
70
+ if (typeof remote !== 'string') {
71
+ throw new Error('remote must be a string');
72
+ }
73
+
74
+ if (remote.includes('@')) {
75
+ const [url, global] = extractUrlAndGlobal(remote);
76
+ if (
77
+ !['window.', 'global.', 'globalThis.'].some((prefix) =>
78
+ global.startsWith(prefix),
79
+ )
80
+ ) {
81
+ return `globalThis.__remote_scope__.${global}@${url}`;
82
+ }
83
+ }
84
+ return remote;
85
+ };
86
+
87
+ /**
88
+ * Class representing a NodeFederationPlugin.
89
+ * @class
90
+ */
91
+ class NodeFederationPlugin {
92
+ private _options: ModuleFederationPluginOptions;
93
+ private context: Context;
94
+ private experiments: NodeFederationOptions['experiments'];
95
+
96
+ /**
97
+ * Create a NodeFederationPlugin.
98
+ * @constructor
99
+ * @param {NodeFederationOptions} options - The options for the NodeFederationPlugin
100
+ * @param {Context} context - The context for the NodeFederationPlugin
101
+ */
102
+ constructor(
103
+ { experiments, debug, ...options }: NodeFederationOptions,
104
+ context: Context,
105
+ ) {
106
+ this._options = options || ({} as ModuleFederationPluginOptions);
107
+ this.context = context || ({} as Context);
108
+ this.experiments = experiments || {};
109
+ }
110
+
111
+ /**
112
+ * Apply method for the NodeFederationPlugin class.
113
+ * @method
114
+ * @param {Compiler} compiler - The webpack compiler.
115
+ */
116
+ apply(compiler: Compiler) {
117
+ const { webpack } = compiler;
118
+ new ModuleInfoRuntimePlugin().apply(compiler);
119
+ const pluginOptions = this.preparePluginOptions();
120
+ this.updateCompilerOptions(compiler);
121
+ const ModuleFederationPlugin = this.getModuleFederationPlugin(
122
+ compiler,
123
+ webpack,
124
+ );
125
+ new ModuleFederationPlugin(pluginOptions).apply(compiler);
126
+ }
127
+
128
+ private preparePluginOptions(): ModuleFederationPluginOptions {
129
+ return {
130
+ ...this._options,
131
+ remotes: this._options.remotes
132
+ ? parseRemotes(this._options.remotes as Record<string, any>)
133
+ : {},
134
+ };
135
+ }
136
+
137
+ private updateCompilerOptions(compiler: Compiler): void {
138
+ if (compiler.options && compiler.options.output) {
139
+ compiler.options.output.importMetaName = 'remoteContainerRegistry';
140
+ }
141
+ const chunkFileName = compiler.options?.output?.chunkFilename;
142
+ const uniqueName =
143
+ compiler?.options?.output?.uniqueName || this._options.name;
144
+ if (
145
+ typeof chunkFileName === 'string' &&
146
+ uniqueName &&
147
+ !chunkFileName.includes(uniqueName)
148
+ ) {
149
+ const suffix = `-[chunkhash].js`;
150
+ compiler.options.output.chunkFilename = chunkFileName.replace(
151
+ '.js',
152
+ suffix,
153
+ );
154
+ }
155
+ }
156
+
157
+ private getModuleFederationPlugin(compiler: Compiler, webpack: any): any {
158
+ let ModuleFederationPlugin;
159
+ if (this.context.ModuleFederationPlugin) {
160
+ ModuleFederationPlugin = this.context.ModuleFederationPlugin;
161
+ } else if (
162
+ webpack &&
163
+ webpack.container &&
164
+ webpack.container.ModuleFederationPlugin
165
+ ) {
166
+ ModuleFederationPlugin = webpack.container.ModuleFederationPlugin;
167
+ } else {
168
+ ModuleFederationPlugin = this.loadModuleFederationPlugin();
169
+ }
170
+ return ModuleFederationPlugin;
171
+ }
172
+
173
+ private loadModuleFederationPlugin(): any {
174
+ let ModuleFederationPlugin;
175
+ try {
176
+ ModuleFederationPlugin =
177
+ require('@module-federation/enhanced').ModuleFederationPlugin;
178
+ } catch (e) {
179
+ ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin');
180
+ }
181
+ return ModuleFederationPlugin;
182
+ }
183
+ }
184
+
185
+ export default NodeFederationPlugin;
@@ -0,0 +1,137 @@
1
+ import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
2
+ const { RuntimeGlobals, RuntimeModule, Template, javascript } = require(
3
+ normalizeWebpackPath('webpack'),
4
+ ) as typeof import('webpack');
5
+ const { getUndoPath } = require(
6
+ normalizeWebpackPath('webpack/lib/util/identifier'),
7
+ ) as typeof import('webpack/lib/util/identifier');
8
+
9
+ class AutoPublicPathRuntimeModule extends RuntimeModule {
10
+ private options: any;
11
+
12
+ constructor(options: any) {
13
+ super('publicPath', RuntimeModule.STAGE_BASIC + 1);
14
+ this.options = options;
15
+ }
16
+
17
+ /**
18
+ * @returns {string} runtime code
19
+ */
20
+ override generate() {
21
+ const { compilation } = this;
22
+ const {
23
+ scriptType,
24
+ path,
25
+ publicPath,
26
+ importMetaName,
27
+ uniqueName,
28
+ chunkLoading,
29
+ //@ts-ignore
30
+ } = compilation.outputOptions;
31
+
32
+ const getPath = () =>
33
+ compilation?.getPath(publicPath || '', {
34
+ hash: compilation?.hash || 'XXXX',
35
+ });
36
+ // If publicPath is not "auto", return the static value
37
+ // if (publicPath !== 'auto') {
38
+ // const path = getPath();
39
+ // return Template.asString([
40
+ // `${RuntimeGlobals.publicPath} = ${JSON.stringify(path)};`,
41
+ // 'var addProtocol = (url)=> url.startsWith(\'//\') ? \'https:\' + url : url;',
42
+ // `globalThis.currentVmokPublicPath = addProtocol(${RuntimeGlobals.publicPath}) || '/';`,
43
+ // ]);
44
+ // }
45
+ const chunkName = compilation?.getPath(
46
+ javascript.JavascriptModulesPlugin.getChunkFilenameTemplate(
47
+ this.chunk,
48
+ compilation?.outputOptions,
49
+ ),
50
+ {
51
+ chunk: this.chunk,
52
+ contentHashType: 'javascript',
53
+ },
54
+ );
55
+ const undoPath = getUndoPath(chunkName, path, false);
56
+ const ident = Template.toIdentifier(uniqueName || '');
57
+
58
+ // Define potential lookup keys
59
+ const potentialLookups = [this.chunk?.name, ident, uniqueName];
60
+
61
+ // Generate lookup string using potential keys
62
+ const lookupString = potentialLookups
63
+ .filter(Boolean)
64
+ .map((lookup) => {
65
+ return `remoteReg[${JSON.stringify(lookup)}]`;
66
+ })
67
+ .join(' || ');
68
+
69
+ return Template.asString([
70
+ 'var scriptUrl;',
71
+ // its an esproxy so nesting into _config directly is not possible
72
+ `
73
+ let remoteContainerRegistry = {
74
+ get url() {
75
+ var remoteReg = globalThis.__remote_scope__ ? globalThis.__remote_scope__._config : {};
76
+ return ${lookupString}
77
+ }
78
+ };
79
+ `,
80
+
81
+ ['module', 'node', 'async-node', 'require'].includes(scriptType || '') ||
82
+ chunkLoading
83
+ ? Template.asString([
84
+ 'try {',
85
+ Template.indent([
86
+ `scriptUrl = new Function('return typeof ${importMetaName}.url === "string" ? ${importMetaName}.url : undefined;')();`,
87
+ ]),
88
+ '} catch (e) {',
89
+ Template.indent([
90
+ 'if (typeof remoteContainerRegistry.url === "string") {',
91
+ Template.indent('scriptUrl = remoteContainerRegistry.url;'),
92
+ '} else if(typeof __filename !== "undefined") {',
93
+ Template.indent('scriptUrl = __filename;'),
94
+ '} else {',
95
+ Template.indent([
96
+ `scriptUrl = ${
97
+ publicPath !== 'auto'
98
+ ? JSON.stringify(getPath())
99
+ : 'undefined'
100
+ }`,
101
+ ]),
102
+ '}',
103
+ ]),
104
+ '}',
105
+ ])
106
+ : Template.asString([
107
+ `if (${RuntimeGlobals.global}.importScripts) scriptUrl = ${RuntimeGlobals.global}.location + "";`,
108
+ `var document = ${RuntimeGlobals.global}.document;`,
109
+ 'if (!scriptUrl && document) {',
110
+ Template.indent([
111
+ 'if (document.currentScript)',
112
+ Template.indent('scriptUrl = document.currentScript.src'),
113
+ 'if (!scriptUrl) {',
114
+ Template.indent([
115
+ 'var scripts = document.getElementsByTagName("script");',
116
+ 'if(scripts.length) scriptUrl = scripts[scripts.length - 1].src',
117
+ ]),
118
+ '}',
119
+ ]),
120
+ '}',
121
+ ]),
122
+ '// When supporting server environments where an automatic publicPath is not supported, you must specify an output.publicPath manually via configuration',
123
+ '// or pass an empty string ("") and set the __webpack_public_path__ variable from your code to use your own logic.',
124
+ 'if (!scriptUrl) throw new Error("Unable to calculate automatic public path");',
125
+ 'scriptUrl = scriptUrl.replace(/#.*$/, "").replace(/\\?.*$/, "").replace(/\\/[^\\/]+$/, "/");',
126
+ !undoPath
127
+ ? `${RuntimeGlobals.publicPath} = scriptUrl;`
128
+ : `${RuntimeGlobals.publicPath} = scriptUrl + ${JSON.stringify(
129
+ undoPath,
130
+ )};`,
131
+ "var addProtocol = (url)=> url.startsWith('//') ? 'https:' + url : url;",
132
+ `globalThis.currentVmokPublicPath = addProtocol(${RuntimeGlobals.publicPath}) || '/';`,
133
+ ]);
134
+ }
135
+ }
136
+
137
+ export default AutoPublicPathRuntimeModule;
@@ -0,0 +1,88 @@
1
+ # StreamingTargetPlugin
2
+
3
+ ## Overview
4
+
5
+ The `StreamingTargetPlugin` is designed to introduce a new transport layer for Webpack. It enables the streaming of chunks in Node.js environments, even when the chunks are not readily available on disk. This plugin is an excellent alternative to Webpack's `CommonJsChunkLoadingPlugin`, offering similar functionality without the need for a coupled filesystem.
6
+
7
+ ## Installation
8
+
9
+ You can install the `StreamingTargetPlugin` via npm or yarn using the following command:
10
+ `npm install @module-federation/node`
11
+
12
+ ## Prerequisites
13
+
14
+ The `StreamingTargetPlugin` is typically used in combination with either the `NodeFederationPlugin` or the `UniversalFederationPlugin`.
15
+
16
+ ## Usage
17
+
18
+ ### With NodeFederationPlugin
19
+
20
+ ```javascript
21
+ const { NodeFederationPlugin, StreamingTargetPlugin } = require('@module-federation/node');
22
+ const config = {
23
+ target: isServer ? false : 'web',
24
+ plugins: [
25
+ new NodeFederationPlugin({
26
+ name: 'website2',
27
+ library: { type: 'commonjs-module' },
28
+ remotes: {},
29
+ filename: 'remoteEntry.js',
30
+ exposes: {
31
+ './SharedComponent': './remoteServer/SharedComponent',
32
+ },
33
+ }),
34
+ new StreamingTargetPlugin({
35
+ name: 'website2',
36
+ library: { type: 'commonjs-module' },
37
+ remotes: {},
38
+ }),
39
+ ],
40
+ };
41
+ ```
42
+
43
+ ### With UniversalFederationPlugin
44
+
45
+ ```javascript
46
+ const { UniversalFederationPlugin } = require('@module-federation/node');
47
+ const config = {
48
+ target: isServer ? false : 'web',
49
+ plugins: [
50
+ new UniversalFederationPlugin({
51
+ name: 'website2',
52
+ library: { type: 'commonjs-module' },
53
+ isServer: true, // or false
54
+ remotes: {},
55
+ filename: 'remoteEntry.js',
56
+ exposes: {
57
+ './SharedComponent': './remoteServer/SharedComponent',
58
+ },
59
+ }),
60
+ ],
61
+ };
62
+ ```
63
+
64
+ ## Options
65
+
66
+ - `name`: The name of the federated module.
67
+ - `library`: The type of module, usually `commonjs-module`.
68
+ - `remotes`: An object specifying the remote federated modules.
69
+ - `promiseBaseURI`: The base URI for the promise. Optional.
70
+ - `debug`: Flag to enable/disable debug mode. Optional.
71
+
72
+ ## Roadmap
73
+
74
+ For future plans and improvements, refer to the [Roadmap/RFC](https://github.com/module-federation/universe/discussions/1170).
75
+
76
+ ## Contributing
77
+
78
+ Contribution guidelines to be provided by package maintainer.
79
+
80
+ ## License
81
+
82
+ License information to be provided by package maintainer.
83
+
84
+ ---
85
+
86
+ URLs:
87
+
88
+ - Roadmap/RFC: https://github.com/module-federation/universe/discussions/1170
@@ -0,0 +1,81 @@
1
+ import type { Compiler, WebpackPluginInstance } from 'webpack';
2
+ import type { ModuleFederationPluginOptions } from '../types';
3
+
4
+ import CommonJsChunkLoadingPlugin from './CommonJsChunkLoadingPlugin';
5
+
6
+ /**
7
+ * Interface for StreamingTargetOptions which extends ModuleFederationPluginOptions
8
+ * @property {string} promiseBaseURI - The base URI for the promise
9
+ * @property {boolean} debug - Flag to enable/disable debug mode
10
+ */
11
+ interface StreamingTargetOptions extends ModuleFederationPluginOptions {
12
+ promiseBaseURI?: string;
13
+ debug?: boolean;
14
+ }
15
+
16
+ // eslint-disable-next-line @typescript-eslint/no-empty-interface
17
+ /**
18
+ * Interface for StreamingTargetContext
19
+ */
20
+ interface StreamingTargetContext {}
21
+
22
+ /**
23
+ * Class representing a StreamingTargetPlugin
24
+ */
25
+ class StreamingTargetPlugin implements WebpackPluginInstance {
26
+ private options: StreamingTargetOptions;
27
+
28
+ /**
29
+ * Create a StreamingTargetPlugin
30
+ * @param {StreamingTargetOptions} options - The options for the plugin
31
+ */
32
+ constructor(options: StreamingTargetOptions) {
33
+ this.options = options || {};
34
+ }
35
+
36
+ /**
37
+ * Apply the plugin to the compiler
38
+ * @param {Compiler} compiler - The webpack compiler
39
+ */
40
+ apply(compiler: Compiler) {
41
+ // When used with Next.js, context is needed to use Next.js webpack
42
+ const { webpack } = compiler;
43
+
44
+ compiler.options.output.chunkFormat = 'commonjs';
45
+ if (compiler.options.output.enabledLibraryTypes === undefined) {
46
+ compiler.options.output.enabledLibraryTypes = ['commonjs-module'];
47
+ } else {
48
+ compiler.options.output.enabledLibraryTypes.push('commonjs-module');
49
+ }
50
+
51
+ compiler.options.output.chunkLoading = 'async-node';
52
+
53
+ // Disable default config
54
+ // FIXME: enabledChunkLoadingTypes is of type 'string[] | undefined'
55
+ // Can't use the 'false' value as it isn't the right format,
56
+ // Emptying it out ensures theres no other readFileVm added to webpack runtime
57
+ compiler.options.output.enabledChunkLoadingTypes = [];
58
+ compiler.options.output.environment = {
59
+ ...compiler.options.output.environment,
60
+ dynamicImport: true,
61
+ };
62
+
63
+ new (webpack?.node?.NodeEnvironmentPlugin ||
64
+ require('webpack/lib/node/NodeEnvironmentPlugin'))({
65
+ infrastructureLogging: compiler.options.infrastructureLogging,
66
+ }).apply(compiler);
67
+
68
+ new (webpack?.node?.NodeTargetPlugin ||
69
+ require('webpack/lib/node/NodeTargetPlugin'))().apply(compiler);
70
+ new CommonJsChunkLoadingPlugin({
71
+ asyncChunkLoading: true,
72
+ name: this.options.name,
73
+ remotes: this.options.remotes as Record<string, string>,
74
+ baseURI: compiler.options.output.publicPath,
75
+ promiseBaseURI: this.options.promiseBaseURI,
76
+ debug: this.options.debug,
77
+ }).apply(compiler);
78
+ }
79
+ }
80
+
81
+ export default StreamingTargetPlugin;
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Importing necessary plugins and types
3
+ */
4
+ import StreamingTargetPlugin from './StreamingTargetPlugin';
5
+ import NodeFederationPlugin from './NodeFederationPlugin';
6
+ import { ModuleFederationPluginOptions } from '../types';
7
+ import type { Compiler, container } from 'webpack';
8
+ import {
9
+ getWebpackPath,
10
+ normalizeWebpackPath,
11
+ } from '@module-federation/sdk/normalize-webpack-path';
12
+
13
+ /**
14
+ * Interface for NodeFederationOptions
15
+ * @property {boolean} isServer - Indicates if the server is running
16
+ * @property {string} [promiseBaseURI] - The base URI for the promise
17
+ * @property {boolean} [debug] - Indicates if debug mode is enabled
18
+ */
19
+ interface NodeFederationOptions extends ModuleFederationPluginOptions {
20
+ isServer: boolean;
21
+ promiseBaseURI?: string;
22
+ debug?: boolean;
23
+ }
24
+
25
+ /**
26
+ * Interface for NodeFederationContext
27
+ * @property {typeof container.ModuleFederationPlugin} [ModuleFederationPlugin] - The ModuleFederationPlugin from webpack container
28
+ */
29
+ interface NodeFederationContext {
30
+ ModuleFederationPlugin?: typeof container.ModuleFederationPlugin;
31
+ }
32
+
33
+ /**
34
+ * Class representing a UniversalFederationPlugin
35
+ */
36
+ class UniversalFederationPlugin {
37
+ private _options: NodeFederationOptions;
38
+ private context: NodeFederationContext;
39
+
40
+ /**
41
+ * Create a UniversalFederationPlugin
42
+ * @param {NodeFederationOptions} options - The options for the plugin
43
+ * @param {NodeFederationContext} context - The context for the plugin
44
+ */
45
+ constructor(options: NodeFederationOptions, context: NodeFederationContext) {
46
+ this._options = options || ({} as NodeFederationOptions);
47
+ this.context = context || ({} as NodeFederationContext);
48
+ }
49
+
50
+ /**
51
+ * Apply the plugin to the compiler
52
+ * @param {Compiler} compiler - The webpack compiler
53
+ */
54
+ apply(compiler: Compiler) {
55
+ const { isServer, debug, ...options } = this._options;
56
+ const { webpack } = compiler;
57
+ if (!process.env['FEDERATION_WEBPACK_PATH']) {
58
+ process.env['FEDERATION_WEBPACK_PATH'] = getWebpackPath(compiler);
59
+ }
60
+ if (
61
+ isServer ||
62
+ compiler.options.name === 'server' ||
63
+ compiler.options.target === 'node' ||
64
+ compiler.options.target === 'async-node'
65
+ ) {
66
+ new NodeFederationPlugin(options, this.context).apply(compiler);
67
+ new StreamingTargetPlugin({ ...options, debug }).apply(compiler);
68
+ } else {
69
+ new (this.context.ModuleFederationPlugin ||
70
+ (webpack && webpack.container.ModuleFederationPlugin) ||
71
+ require(
72
+ normalizeWebpackPath('webpack/lib/container/ModuleFederationPlugin'),
73
+ ))(options).apply(compiler);
74
+ }
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Exporting UniversalFederationPlugin as default
80
+ */
81
+ export default UniversalFederationPlugin;