-
-
Notifications
You must be signed in to change notification settings - Fork 393
Expand file tree
/
Copy pathModuleFederationPlugin.ts
More file actions
249 lines (225 loc) · 8.25 KB
/
ModuleFederationPlugin.ts
File metadata and controls
249 lines (225 loc) · 8.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra and Zackary Jackson @ScriptedAlchemy
*/
'use strict';
import { DtsPlugin } from '@module-federation/dts-plugin';
import { ContainerManager, utils } from '@module-federation/managers';
import { StatsPlugin } from '@module-federation/manifest';
import {
bindLoggerToCompiler,
composeKeyWithSeparator,
type moduleFederationPlugin,
infrastructureLogger,
} from '@module-federation/sdk';
import { PrefetchPlugin } from '@module-federation/data-prefetch/cli';
import { normalizeWebpackPath } from '@module-federation/sdk/normalize-webpack-path';
import type { Compiler, WebpackPluginInstance } from 'webpack';
import SharePlugin from '../sharing/SharePlugin';
import ContainerPlugin from './ContainerPlugin';
import ContainerReferencePlugin from './ContainerReferencePlugin';
import FederationRuntimePlugin from './runtime/FederationRuntimePlugin';
import { RemoteEntryPlugin } from '@module-federation/rspack/remote-entry-plugin';
import { ExternalsType } from 'webpack/declarations/WebpackOptions';
import StartupChunkDependenciesPlugin from '../startup/MfStartupChunkDependenciesPlugin';
import FederationModulesPlugin from './runtime/FederationModulesPlugin';
import { createSchemaValidation } from '../../utils';
import TreeShakingSharedPlugin from '../sharing/tree-shaking/TreeShakingSharedPlugin';
const isValidExternalsType = require(
normalizeWebpackPath(
'webpack/schemas/plugins/container/ExternalsType.check.js',
),
) as typeof import('webpack/schemas/plugins/container/ExternalsType.check.js');
const { ExternalsPlugin } = require(
normalizeWebpackPath('webpack'),
) as typeof import('webpack');
const validate = createSchemaValidation(
//eslint-disable-next-line
require('../../schemas/container/ModuleFederationPlugin.check.js').validate,
() => require('../../schemas/container/ModuleFederationPlugin').default,
{
name: 'Module Federation Plugin',
baseDataPath: 'options',
},
);
class ModuleFederationPlugin implements WebpackPluginInstance {
private _options: moduleFederationPlugin.ModuleFederationPluginOptions;
private _statsPlugin?: StatsPlugin;
/**
* @param {moduleFederationPlugin.ModuleFederationPluginOptions} options options
*/
constructor(options: moduleFederationPlugin.ModuleFederationPluginOptions) {
validate(options);
this._options = options;
}
private _patchBundlerConfig(compiler: Compiler): void {
const { name, experiments } = this._options;
const definePluginOptions: Record<string, string | boolean> = {};
const MFPluginNum = compiler.options.plugins.filter(
(p): p is WebpackPluginInstance =>
!!p && (p as any).name === 'ModuleFederationPlugin',
).length;
if (name && MFPluginNum < 2) {
definePluginOptions['FEDERATION_BUILD_IDENTIFIER'] = JSON.stringify(
composeKeyWithSeparator(name, utils.getBuildVersion()),
);
}
const disableSnapshot = experiments?.optimization?.disableSnapshot ?? false;
definePluginOptions['FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN'] =
disableSnapshot;
// Determine ENV_TARGET: only if manually specified in experiments.optimization.target
if (
experiments?.optimization &&
typeof experiments.optimization === 'object' &&
experiments.optimization !== null &&
'target' in experiments.optimization
) {
const manualTarget = experiments.optimization.target as
| 'web'
| 'node'
| undefined;
// Ensure the target is one of the expected values before setting
if (manualTarget === 'web' || manualTarget === 'node') {
definePluginOptions['ENV_TARGET'] = JSON.stringify(manualTarget);
}
}
// No inference for ENV_TARGET. If not manually set and valid, it's not defined.
new compiler.webpack.DefinePlugin(definePluginOptions).apply(compiler);
}
/**
* Apply the plugin
* @param {Compiler} compiler the compiler instance
* @returns {void}
*/
apply(compiler: Compiler): void {
bindLoggerToCompiler(
infrastructureLogger,
compiler,
'EnhancedModuleFederationPlugin',
);
const { _options: options } = this;
const { name, experiments, dts, remotes, shared, shareScope } = options;
if (!name) {
// TODO: remove the comment
throw new Error('ModuleFederationPlugin name is required');
}
// must before ModuleFederationPlugin
(new RemoteEntryPlugin(options) as unknown as WebpackPluginInstance).apply(
compiler,
);
if (experiments?.provideExternalRuntime) {
if (options.exposes) {
throw new Error(
'You can only set provideExternalRuntime: true in pure consumer which not expose modules.',
);
}
const runtimePlugins = options.runtimePlugins || [];
options.runtimePlugins = runtimePlugins.concat(
require.resolve(
'@module-federation/inject-external-runtime-core-plugin',
),
);
}
if (experiments?.externalRuntime === true) {
const Externals = compiler.webpack.ExternalsPlugin || ExternalsPlugin;
new Externals(compiler.options.externalsType || 'global', {
'@module-federation/runtime-core': '_FEDERATION_RUNTIME_CORE',
}).apply(compiler);
}
// federation hooks
new FederationModulesPlugin().apply(compiler);
if (experiments?.asyncStartup) {
new StartupChunkDependenciesPlugin({
asyncChunkLoading: true,
}).apply(compiler);
}
if (dts !== false) {
const dtsPlugin = new DtsPlugin(options);
dtsPlugin.apply(compiler);
dtsPlugin.addRuntimePlugins();
}
// TODO: REMOVE in next major version
if (options.dataPrefetch) {
new PrefetchPlugin(options).apply(compiler);
}
new FederationRuntimePlugin(options).apply(compiler);
const library = options.library || { type: 'var', name: name };
const remoteType =
options.remoteType ||
(options.library && isValidExternalsType(options.library.type)
? (options.library.type as ExternalsType)
: ('script' as ExternalsType));
const useContainerPlugin =
options.exposes &&
(Array.isArray(options.exposes)
? options.exposes.length > 0
: Object.keys(options.exposes).length > 0);
let disableManifest = options.manifest === false;
if (useContainerPlugin) {
ContainerPlugin.patchChunkSplit(compiler, name);
}
this._patchBundlerConfig(compiler);
if (!disableManifest && useContainerPlugin) {
try {
const containerManager = new ContainerManager();
containerManager.init(options);
options.exposes = containerManager.containerPluginExposesOptions;
} catch (err) {
if (err instanceof Error) {
err.message = `[ ModuleFederationPlugin ]: Manifest will not generate, because: ${err.message}`;
}
infrastructureLogger.warn(err);
disableManifest = true;
}
}
if (
library &&
!compiler.options.output.enabledLibraryTypes?.includes(library.type)
) {
compiler.options.output.enabledLibraryTypes?.push(library.type);
}
compiler.hooks.afterPlugins.tap('ModuleFederationPlugin', () => {
if (useContainerPlugin) {
new ContainerPlugin({
name,
library,
filename: options.filename,
runtime: options.runtime,
shareScope: options.shareScope,
exposes: options.exposes!,
runtimePlugins: options.runtimePlugins,
}).apply(compiler);
}
if (
remotes &&
(Array.isArray(remotes)
? remotes.length > 0
: Object.keys(remotes).length > 0)
) {
new ContainerReferencePlugin({
remoteType,
shareScope,
remotes,
}).apply(compiler);
}
if (shared) {
new TreeShakingSharedPlugin({
mfConfig: options,
}).apply(compiler);
new SharePlugin({
shared,
shareScope,
}).apply(compiler);
}
});
if (!disableManifest) {
const pkg = require('../../../../package.json');
this._statsPlugin = new StatsPlugin(options, {
pluginVersion: pkg.version,
bundler: 'webpack',
});
this._statsPlugin.apply(compiler);
}
}
}
export default ModuleFederationPlugin;