-
-
Notifications
You must be signed in to change notification settings - Fork 401
Expand file tree
/
Copy pathindex.ts
More file actions
540 lines (486 loc) · 17.9 KB
/
index.ts
File metadata and controls
540 lines (486 loc) · 17.9 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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
import {
ModuleFederationPlugin,
TreeShakingSharedPlugin,
PLUGIN_NAME,
parseOptions,
} from '@module-federation/enhanced/rspack';
import { isRequiredVersion, getManifestFileName } from '@module-federation/sdk';
import pkgJson from '../../package.json';
import logger from '../logger';
import {
isRegExp,
autoDeleteSplitChunkCacheGroups,
addDataFetchExposes,
createSSRMFConfig,
createSSRREnvConfig,
setSSREnv,
SSR_ENV_NAME,
SSR_DIR,
updateStatsAndManifest,
StatsAssetResource,
patchSSRRspackConfig,
} from '../utils';
import type { moduleFederationPlugin } from '@module-federation/sdk';
import type { RsbuildConfig, RsbuildPlugin, Rspack } from '@rsbuild/core';
import {
CALL_NAME_MAP,
RSPRESS_BUNDLER_CONFIG_NAME,
RSPRESS_SSR_DIR,
} from '../constant';
import {
ENV_NAME,
patchNodeConfig,
patchNodeMFConfig,
patchToolsTspack,
} from '../utils/ssr';
type ModuleFederationOptions =
moduleFederationPlugin.ModuleFederationPluginOptions;
type RSBUILD_PLUGIN_OPTIONS = {
target?: 'web' | 'node' | 'dual';
/**
* @deprecated Please use `target: 'dual'` instead.
*/
ssr?: boolean;
// ssr dir, default is ssr
ssrDir?: string;
// target copy environment name, default is mf
environment?: string;
};
type ExposedAPIType = {
options: {
nodePlugin?: ModuleFederationPlugin;
browserPlugin?: ModuleFederationPlugin;
rspressSSGPlugin?: ModuleFederationPlugin;
distOutputDir?: string;
browserEnvironmentName?: string;
nodeEnvironmentName?: string;
};
assetResources: Record<string, StatsAssetResource>;
isSSRConfig: typeof isSSRConfig;
isRspressSSGConfig: typeof isRspressSSGConfig;
};
export type { ModuleFederationOptions, ExposedAPIType };
const RSBUILD_PLUGIN_MODULE_FEDERATION_NAME =
'rsbuild:module-federation-enhanced';
const RSBUILD_PLUGIN_NAME = '@module-federation/rsbuild-plugin';
export { RSBUILD_PLUGIN_MODULE_FEDERATION_NAME, PLUGIN_NAME, SSR_DIR };
const LIB_FORMAT = ['umd', 'modern-module'];
const DEFAULT_MF_ENVIRONMENT_NAME = 'mf';
function isStoryBook(rsbuildConfig: RsbuildConfig) {
if (
rsbuildConfig.plugins?.find(
(p) =>
p && 'name' in p && p.name === 'module-federation-storybook-plugin',
)
) {
return true;
}
return false;
}
export function isMFFormat(bundlerConfig: Rspack.Configuration) {
const library = bundlerConfig.output?.library;
if (bundlerConfig.name === SSR_ENV_NAME) {
return true;
}
return !(
typeof library === 'object' &&
!Array.isArray(library) &&
'type' in library &&
// if the type is umd/modern-module or commonjs*, means this is a normal library , not mf
(LIB_FORMAT.includes(library.type) || /commonjs/.test(library.type))
);
}
const isSSRConfig = (bundlerConfigName?: string) =>
Boolean(bundlerConfigName === SSR_ENV_NAME);
const isRspressSSGConfig = (bundlerConfigName?: string) => {
return bundlerConfigName === RSPRESS_BUNDLER_CONFIG_NAME;
};
export const pluginModuleFederation = (
moduleFederationOptions: ModuleFederationOptions,
rsbuildOptions?: RSBUILD_PLUGIN_OPTIONS,
): RsbuildPlugin => ({
name: RSBUILD_PLUGIN_MODULE_FEDERATION_NAME,
setup: (api) => {
const {
target = 'web',
ssr = undefined,
ssrDir = SSR_DIR,
environment = DEFAULT_MF_ENVIRONMENT_NAME,
} = rsbuildOptions || {};
if (ssr) {
throw new Error(
"The `ssr` option is deprecated. If you want to enable SSR, please use `target: 'dual'` instead.",
);
}
const { callerName } = api.context;
const originalRsbuildConfig = api.getRsbuildConfig();
if (!callerName) {
throw new Error(
'`callerName` is undefined. Please ensure the @rsbuild/core version is higher than 1.3.21 .',
);
}
const isRslib = callerName === CALL_NAME_MAP.RSLIB;
const isRspress = callerName === CALL_NAME_MAP.RSPRESS;
const isSSR = target === 'dual';
if (isSSR && !isStoryBook(originalRsbuildConfig)) {
if (!isRslib && !isRspress) {
throw new Error(`'target' option is only supported in Rslib.`);
}
const rsbuildConfig = api.getRsbuildConfig();
if (
!rsbuildConfig.environments?.[environment] ||
Object.keys(rsbuildConfig.environments).some(
(key) => key.startsWith(environment) && key !== environment,
)
) {
throw new Error(
`Please set ${RSBUILD_PLUGIN_NAME} as global plugin in rslib.config.ts if you set 'target: "dual"'.`,
);
}
setSSREnv();
}
const sharedOptions: [string, moduleFederationPlugin.SharedConfig][] =
parseOptions(
moduleFederationOptions.shared || [],
(item: string | string[], key: string) => {
if (typeof item !== 'string')
throw new Error('Unexpected array in shared');
const config: moduleFederationPlugin.SharedConfig =
item === key || !isRequiredVersion(item)
? {
import: item,
}
: {
import: key,
requiredVersion: item,
};
return config;
},
(item: any) => item,
);
// shared[0] is the shared name
const shared = sharedOptions.map((shared) =>
shared[0].endsWith('/') ? shared[0].slice(0, -1) : shared[0],
);
api.modifyRsbuildConfig((config) => {
// skip storybook
if (isStoryBook(config)) {
return;
}
// Change some default configs for remote modules
if (moduleFederationOptions.exposes) {
config.dev ||= {};
config.server ||= {};
const userConfig = api.getRsbuildConfig('original');
// Allow remote modules to be loaded by setting CORS headers
// This is required for MF to work properly across different origins
config.server.headers ||= {};
if (
!config.server.headers['Access-Control-Allow-Origin'] &&
!(
typeof userConfig.server?.cors === 'object' &&
userConfig.server.cors.origin
)
) {
const corsWarnMsgs = [
'Detect that CORS options are not set, mf Rsbuild plugin will add default cors header: server.headers["Access-Control-Allow-Headers"] = "*". It is recommended to specify an allowlist of trusted origins in "server.cors" instead.',
'View https://module-federation.io/guide/troubleshooting/other.html#cors-warn for more details.',
];
!isRslib && !isRspress && logger.warn(corsWarnMsgs.join('\n'));
config.server.headers['Access-Control-Allow-Origin'] = '*';
}
// For remote modules, Rsbuild should send the ws request to the provider's dev server.
// This allows the provider to do HMR when the provider module is loaded in the consumer's page.
if (config.server?.port && !config.dev.client?.port) {
config.dev.client ||= {};
config.dev.client.port = config.server.port;
}
// Change the default assetPrefix to `true` for remote modules.
// This ensures that the remote module's assets can be requested by consumer apps with the correct URL.
const originalConfig = api.getRsbuildConfig('original');
if (
originalConfig.dev?.assetPrefix === undefined &&
config.dev.assetPrefix === config.server?.base
) {
config.dev.assetPrefix = true;
}
}
if (isSSR) {
if (config.environments?.[SSR_ENV_NAME]) {
throw new Error(
`'${SSR_ENV_NAME}' environment is already defined.Please use another name.`,
);
}
config.environments![SSR_ENV_NAME] = createSSRREnvConfig(
config.environments?.[environment]!,
moduleFederationOptions,
ssrDir,
config,
callerName,
);
} else if (target === 'node') {
const mfEnv = config.environments![ENV_NAME]!;
patchToolsTspack(mfEnv, (config, { environment }) => {
config.target = 'async-node';
});
}
});
api.modifyEnvironmentConfig((config) => {
// Module Federation runtime uses ES6+ syntax,
// adding to include and let SWC transform it
config.source.include = [
...(config.source.include || []),
/@module-federation[\\/]/,
];
return config;
});
const generateMergedStatsAndManifestOptions: ExposedAPIType = {
options: {
nodePlugin: undefined,
browserPlugin: undefined,
rspressSSGPlugin: undefined,
distOutputDir: undefined,
browserEnvironmentName: undefined,
nodeEnvironmentName: undefined,
},
assetResources: {},
isSSRConfig,
isRspressSSGConfig,
};
api.expose(
RSBUILD_PLUGIN_MODULE_FEDERATION_NAME,
generateMergedStatsAndManifestOptions,
);
const defaultBrowserEnvironmentName = environment;
const assetFileNames = getManifestFileName(
moduleFederationOptions.manifest,
);
if (moduleFederationOptions.manifest !== false) {
api.processAssets(
{
stage: 'report',
},
({ assets, environment: envContext }) => {
const expectedBrowserEnv =
generateMergedStatsAndManifestOptions.options
.browserEnvironmentName ?? defaultBrowserEnvironmentName;
const expectedNodeEnv =
generateMergedStatsAndManifestOptions.options.nodeEnvironmentName ??
SSR_ENV_NAME;
const envName = envContext.name;
if (envName !== expectedBrowserEnv && envName !== expectedNodeEnv) {
return;
}
const assetResources =
generateMergedStatsAndManifestOptions.assetResources;
const targetResources =
assetResources[envName] || (assetResources[envName] = {});
const statsAsset = assets[assetFileNames.statsFileName];
if (statsAsset) {
try {
const raw = statsAsset.source();
const content = typeof raw === 'string' ? raw : raw.toString();
targetResources.stats = {
data: JSON.parse(content),
filename: assetFileNames.statsFileName,
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error(
`Failed to parse stats asset "${assetFileNames.statsFileName}" for environment "${envName}": ${message} `,
);
}
}
const manifestAsset = assets[assetFileNames.manifestFileName];
if (manifestAsset) {
try {
const raw = manifestAsset.source();
const content = typeof raw === 'string' ? raw : raw.toString();
targetResources.manifest = {
data: JSON.parse(content),
filename: assetFileNames.manifestFileName,
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error(
`Failed to parse manifest asset "${assetFileNames.manifestFileName}" for environment "${envName}": ${message} `,
);
}
}
},
);
}
api.onBeforeCreateCompiler(({ bundlerConfigs }) => {
if (!bundlerConfigs) {
throw new Error('Can not get bundlerConfigs!');
}
bundlerConfigs.forEach((bundlerConfig) => {
if (!isMFFormat(bundlerConfig) && !isRspress) {
return;
} else if (isStoryBook(originalRsbuildConfig)) {
bundlerConfig.output!.uniqueName = `${moduleFederationOptions.name} -storybook - host`;
} else {
// mf
autoDeleteSplitChunkCacheGroups(
moduleFederationOptions,
bundlerConfig?.optimization?.splitChunks,
);
addDataFetchExposes(
moduleFederationOptions.exposes,
isSSRConfig(bundlerConfig.name),
);
delete bundlerConfig.optimization?.runtimeChunk;
const externals = bundlerConfig.externals;
if (Array.isArray(externals)) {
const sharedModules = new Set<string>();
bundlerConfig.externals = externals.filter((ext) => {
let sharedModule;
if (isRegExp(ext)) {
const match = shared.some((dep) => {
if (
(ext as RegExp).test(dep) ||
(ext as RegExp).test(pkgJson.name)
) {
sharedModule = dep;
return true;
}
return false;
});
match && sharedModule && sharedModules.add(sharedModule);
return !match;
}
if (typeof ext === 'string') {
if (ext === pkgJson.name) {
return false;
}
const match = shared.some((dep) => {
if (dep === ext) {
sharedModule = dep;
}
return dep === ext;
});
if (match) {
sharedModule && sharedModules.add(sharedModule);
return false;
}
return true;
}
return true;
});
if (sharedModules.size > 0) {
for (const sharedModule of sharedModules) {
logger.log(
`${sharedModule} is removed from externals because it is a shared module.`,
);
}
}
}
if (
!bundlerConfig.output?.chunkLoadingGlobal &&
!isSSRConfig(bundlerConfig.name) &&
!isRspressSSGConfig(bundlerConfig.name) &&
target !== 'node'
) {
bundlerConfig.output!.chunkLoading = 'jsonp';
bundlerConfig.output!.chunkLoadingGlobal = `chunk_${moduleFederationOptions.name} `;
}
if (target === 'node' && isMFFormat(bundlerConfig)) {
patchNodeConfig(bundlerConfig, moduleFederationOptions);
patchNodeMFConfig(moduleFederationOptions);
}
// `uniqueName` is required for react refresh to work
if (!bundlerConfig.output?.uniqueName) {
bundlerConfig.output!.uniqueName = moduleFederationOptions.name;
}
// Set default publicPath to 'auto' if not explicitly configured
// This allows remote chunks to load from the same origin as the remote application's manifest
if (
bundlerConfig.output?.publicPath === undefined &&
!isSSRConfig(bundlerConfig.name) &&
!isRspressSSGConfig(bundlerConfig.name)
) {
bundlerConfig.output!.publicPath = 'auto';
}
if (
!bundlerConfig.plugins!.find((p) => p && p.name === PLUGIN_NAME)
) {
if (isSSRConfig(bundlerConfig.name)) {
generateMergedStatsAndManifestOptions.options.nodePlugin =
new ModuleFederationPlugin(
createSSRMFConfig(moduleFederationOptions),
);
generateMergedStatsAndManifestOptions.options.nodeEnvironmentName =
bundlerConfig.name || SSR_ENV_NAME;
bundlerConfig.plugins!.push(
generateMergedStatsAndManifestOptions.options.nodePlugin,
);
return;
} else if (isRspressSSGConfig(bundlerConfig.name)) {
const mfConfig = {
...createSSRMFConfig(moduleFederationOptions),
// expose in mf-ssg env
exposes: {},
manifest: false,
library: undefined,
};
patchSSRRspackConfig(
bundlerConfig,
mfConfig,
RSPRESS_SSR_DIR,
callerName,
false,
false,
);
bundlerConfig.output ||= {};
bundlerConfig.output.publicPath = '/';
// MF depend on asyncChunks
bundlerConfig.output.asyncChunks = undefined;
generateMergedStatsAndManifestOptions.options.rspressSSGPlugin =
new ModuleFederationPlugin(mfConfig);
bundlerConfig.plugins!.push(
generateMergedStatsAndManifestOptions.options.rspressSSGPlugin,
);
return;
}
generateMergedStatsAndManifestOptions.options.browserPlugin =
new ModuleFederationPlugin(moduleFederationOptions);
generateMergedStatsAndManifestOptions.options.distOutputDir =
bundlerConfig.output?.path || '';
generateMergedStatsAndManifestOptions.options.browserEnvironmentName =
bundlerConfig.name || defaultBrowserEnvironmentName;
bundlerConfig.plugins!.push(
generateMergedStatsAndManifestOptions.options.browserPlugin,
);
}
}
});
});
const generateMergedStatsAndManifest = () => {
const { distOutputDir, browserEnvironmentName, nodeEnvironmentName } =
generateMergedStatsAndManifestOptions.options;
if (!distOutputDir || !browserEnvironmentName || !nodeEnvironmentName) {
return;
}
const assetResources =
generateMergedStatsAndManifestOptions.assetResources;
const browserAssets = assetResources[browserEnvironmentName];
const nodeAssets = assetResources[nodeEnvironmentName];
if (!browserAssets || !nodeAssets) {
return;
}
try {
updateStatsAndManifest(nodeAssets, browserAssets, distOutputDir);
} catch (err) {
logger.error(err);
}
};
api.onDevCompileDone(() => {
generateMergedStatsAndManifest();
});
api.onAfterBuild(() => {
generateMergedStatsAndManifest();
});
},
});
export { createModuleFederationConfig } from '@module-federation/sdk';
export { TreeShakingSharedPlugin };