@module-federation/vite 1.0.0-alpha-80b7215 → 1.0.0-alpha-4a73cd4

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.
@@ -1,59 +1,89 @@
1
- import { createFilter } from '@rollup/pluginutils';
2
- import * as path from 'pathe';
3
1
  import * as fs from 'fs';
2
+ import { writeFileSync } from 'fs';
3
+ import * as path from 'pathe';
4
+ import { resolve } from 'pathe';
5
+ import { createFilter } from '@rollup/pluginutils';
4
6
  import { walk } from 'estree-walker';
5
7
  import MagicString from 'magic-string';
6
8
 
7
- var aliasToArrayPlugin = {
8
- name: 'alias-transform-plugin',
9
- config: (config, {
10
- command
11
- }) => {
12
- if (!config.resolve) config.resolve = {};
13
- if (!config.resolve.alias) config.resolve.alias = [];
14
- const {
15
- alias
16
- } = config.resolve;
17
- if (typeof alias === 'object' && !Array.isArray(alias)) {
18
- config.resolve.alias = Object.entries(alias).map(([find, replacement]) => ({
19
- find,
20
- replacement
21
- }));
22
- }
23
- }
24
- };
25
-
26
- var normalizeBuildPlugin = (singleChunkModules => ({
27
- name: 'normalizeBuild',
28
- config: (config, {
29
- command
30
- }) => {
31
- if (!config.build) config.build = {};
32
- if (!config.build.rollupOptions) config.build.rollupOptions = {};
33
- let {
34
- rollupOptions
35
- } = config.build;
36
- if (!rollupOptions.output) rollupOptions.output = {};
37
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
38
- }
39
- }));
40
- function normalizeManualChunks(output, singleChunkModules) {
41
- const pattern = new RegExp(`node_modules/(${singleChunkModules.join('|')})/`);
42
- if (!output.manualChunks) output.manualChunks = {};
43
- const wrapManualChunks = original => (id, ...args) => {
44
- const [_, moduleName] = id.match(pattern) || [];
45
- if (moduleName) {
46
- return moduleName;
47
- }
48
- if (typeof original === 'function') {
49
- return original(id, ...args);
9
+ const addEntry = ({
10
+ entryName,
11
+ entryPath,
12
+ fileName
13
+ }) => {
14
+ let entryFiles = [];
15
+ let htmlFilePath;
16
+ return [{
17
+ name: 'add-entry',
18
+ apply: "serve",
19
+ configureServer(server) {
20
+ var _server$httpServer;
21
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', () => {
22
+ const {
23
+ port
24
+ } = server.config.server;
25
+ fetch(path.join(`http://localhost:${port}`, `${entryPath}`)).catch(e => {});
26
+ });
27
+ server.middlewares.use((req, res, next) => {
28
+ if (!fileName) {
29
+ next();
30
+ return;
31
+ }
32
+ if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
33
+ req.url = entryPath;
34
+ }
35
+ next();
36
+ });
37
+ },
38
+ transformIndexHtml(c) {
39
+ return c.replace('<head>', `<head><script type="module" src=${JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/'))}></script>`);
50
40
  }
51
- if (typeof original === 'object' && original) {
52
- return original[id];
41
+ }, {
42
+ name: "add-entry",
43
+ enforce: "post",
44
+ apply: "build",
45
+ configResolved(config) {
46
+ const inputOptions = config.build.rollupOptions.input;
47
+ if (!inputOptions) {
48
+ htmlFilePath = path.resolve(config.root, 'index.html');
49
+ } else if (typeof inputOptions === 'string') {
50
+ entryFiles = [inputOptions];
51
+ htmlFilePath = path.resolve(config.root, inputOptions);
52
+ } else if (Array.isArray(inputOptions)) {
53
+ entryFiles = inputOptions;
54
+ htmlFilePath = path.resolve(config.root, inputOptions[0]);
55
+ } else if (typeof inputOptions === 'object') {
56
+ entryFiles = Object.values(inputOptions);
57
+ htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
58
+ }
59
+ },
60
+ buildStart() {
61
+ const hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
62
+ this.emitFile({
63
+ [hasHash ? "name" : "fileName"]: fileName,
64
+ type: 'chunk',
65
+ id: entryPath,
66
+ preserveSignature: 'strict'
67
+ });
68
+ if (htmlFilePath) {
69
+ const htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
70
+ const scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
71
+ let match;
72
+ while ((match = scriptRegex.exec(htmlContent)) !== null) {
73
+ entryFiles.push(match[1]);
74
+ }
75
+ }
76
+ },
77
+ transform(code, id) {
78
+ if (entryFiles.some(file => id.endsWith(file))) {
79
+ const injection = `
80
+ import ${JSON.stringify(entryPath)};
81
+ `;
82
+ return injection + code;
83
+ }
53
84
  }
54
- };
55
- output.manualChunks = wrapManualChunks(output.manualChunks);
56
- }
85
+ }];
86
+ };
57
87
 
58
88
  function normalizeExposesItem(key, item) {
59
89
  let importPath = '';
@@ -71,7 +101,7 @@ function normalizeExposes(exposes) {
71
101
  if (!exposes) return {};
72
102
  const res = {};
73
103
  Object.keys(exposes).forEach(key => {
74
- res[key.replace(/^\.?\/?/, './')] = normalizeExposesItem(key, exposes[key]);
104
+ res[key] = normalizeExposesItem(key, exposes[key]);
75
105
  });
76
106
  return res;
77
107
  }
@@ -155,8 +185,12 @@ function normalizeLibrary(library) {
155
185
  if (!library) return undefined;
156
186
  return library;
157
187
  }
188
+ let config;
189
+ function getNormalizeModuleFederationOptions() {
190
+ return config;
191
+ }
158
192
  function normalizeModuleFederationOptions(options) {
159
- return {
193
+ return config = {
160
194
  exposes: normalizeExposes(options.exposes),
161
195
  filename: options.filename || 'remoteEntry-[hash]',
162
196
  library: normalizeLibrary(options.library),
@@ -175,197 +209,82 @@ function normalizeModuleFederationOptions(options) {
175
209
  };
176
210
  }
177
211
 
178
- var normalizeOptimizeDepsPlugin = {
179
- name: 'normalizeOptimizeDeps',
180
- config: (config, {
181
- command
182
- }) => {
183
- let {
184
- optimizeDeps
185
- } = config;
186
- if (!optimizeDeps) {
187
- config.optimizeDeps = {};
188
- optimizeDeps = config.optimizeDeps;
189
- }
190
- if (!optimizeDeps.include) optimizeDeps.include = [];
191
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
192
- }
193
- };
194
-
195
- const addEntry = ({
196
- entryName,
197
- entryPath,
198
- fileName
199
- }) => {
200
- let entryFiles = [];
201
- let htmlFilePath;
202
- return [{
203
- name: 'add-entry',
204
- apply: "serve",
205
- configureServer(server) {
206
- var _server$httpServer;
207
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', () => {
208
- const {
209
- port
210
- } = server.config.server;
211
- fetch(path.join(`http://localhost:${port}`, `${entryPath}`)).catch(e => {});
212
- });
213
- server.middlewares.use((req, res, next) => {
214
- if (!fileName) {
215
- next();
216
- return;
217
- }
218
- if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
219
- req.url = entryPath;
220
- }
221
- next();
222
- });
223
- },
224
- transformIndexHtml(c) {
225
- return c.replace('<head>', `<head><script type="module" src=${JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/'))}></script>`);
226
- }
227
- }, {
228
- name: "add-entry",
229
- enforce: "post",
230
- apply: "build",
231
- configResolved(config) {
232
- const inputOptions = config.build.rollupOptions.input;
233
- if (!inputOptions) {
234
- htmlFilePath = path.resolve(config.root, 'index.html');
235
- } else if (typeof inputOptions === 'string') {
236
- entryFiles = [inputOptions];
237
- htmlFilePath = path.resolve(config.root, inputOptions);
238
- } else if (Array.isArray(inputOptions)) {
239
- entryFiles = inputOptions;
240
- htmlFilePath = path.resolve(config.root, inputOptions[0]);
241
- } else if (typeof inputOptions === 'object') {
242
- entryFiles = Object.values(inputOptions);
243
- htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
244
- }
245
- },
246
- buildStart() {
247
- const hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
248
- this.emitFile({
249
- [hasHash ? "name" : "fileName"]: fileName,
250
- type: 'chunk',
251
- id: entryPath,
252
- preserveSignature: 'strict'
253
- });
254
- if (htmlFilePath) {
255
- const htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
256
- const scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
257
- let match;
258
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
259
- entryFiles.push(match[1]);
260
- }
261
- }
262
- },
263
- transform(code, id) {
264
- if (entryFiles.some(file => id.endsWith(file))) {
265
- const injection = `
266
- import ${JSON.stringify(entryPath)};
267
- `;
268
- return injection + code;
269
- }
270
- }
271
- }];
272
- };
273
-
274
- function overrideModule(options = {}) {
275
- let {
276
- override: _override = [],
277
- include,
278
- exclude
279
- } = options;
280
- const override = new Set(_override);
281
- const filterFunction = createFilter(include, exclude);
282
- const alias = {};
283
- const keys = override.keys();
284
- for (const key of keys) {
285
- alias['__overrideModule__' + key] = require.resolve(`an-empty-js-file`) + `?__overrideModule__=${encodeURIComponent(key)}`;
286
- }
287
- return {
288
- name: 'overrideModule',
289
- enforce: 'post',
290
- config(config) {
291
- if (!config.optimizeDeps) config.optimizeDeps = {};
292
- if (!config.optimizeDeps.needsInterop) config.optimizeDeps.needsInterop = [];
293
- Object.keys(alias).forEach(key => {
294
- var _config$optimizeDeps;
295
- (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(key);
296
- });
297
- config.optimizeDeps.needsInterop.push('an-empty-js-file');
298
- config.resolve.alias.push(...Object.keys(alias).map(key => ({
299
- find: key,
300
- replacement: alias[key]
301
- })));
302
- },
303
- resolveId(id) {
304
- return alias[id];
305
- },
306
- transform: {
307
- handler(code, id) {
308
- if (!filterFunction(id)) return null;
309
- let ast;
310
- try {
311
- ast = this.parse(code, {
312
- allowReturnOutsideFunction: true
313
- });
314
- } catch (e) {
315
- throw new Error(`${id}: ${e}`);
212
+ /**
213
+ * Even the resolveId hook cannot interfere with vite pre-build,
214
+ * and adding query parameter virtual modules will also fail.
215
+ * You can only proxy to the real file through alias
216
+ */
217
+ const emptyNpmDir = resolve(require.resolve("an-empty-js-file"), "../");
218
+ /**
219
+ * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
220
+ */
221
+ const cacheMap2 = {};
222
+ function getPreBuildLibPath(pkg) {
223
+ if (!cacheMap2[pkg]) cacheMap2[pkg] = `__mf__prebuildwrap_${npmPackageNameToFileName(pkg)}.js`;
224
+ const filename = cacheMap2[pkg];
225
+ return filename;
226
+ }
227
+ function getLocalSharedImportMapFileName() {
228
+ const {
229
+ name
230
+ } = getNormalizeModuleFederationOptions();
231
+ return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
232
+ }
233
+ // Only npm package name import can trigger pre-build, absolute path cannot
234
+ function getLocalSharedImportMapId() {
235
+ return `an-empty-js-file/${getLocalSharedImportMapFileName()}`;
236
+ }
237
+ function getLocalSharedImportMapPath() {
238
+ return resolve(emptyNpmDir, getLocalSharedImportMapFileName());
239
+ }
240
+ function writeLocalSharedImportMap(pkgList) {
241
+ writeFileSync(getLocalSharedImportMapPath(), `
242
+ export default {
243
+ ${pkgList.map(pkg => `
244
+ ${JSON.stringify(pkg)}: async () => {
245
+ let pkg = await import("${getPreBuildLibPath(pkg)}")
246
+ return pkg
316
247
  }
317
- const s = new MagicString(code);
318
- walk(ast, {
319
- enter(node) {
320
- const replaceIfMatch = sourceNode => {
321
- if (sourceNode && sourceNode.value) {
322
- if (override.has(sourceNode.value)) {
323
- const start = sourceNode.start + 1; // Skip the opening quote
324
- const end = sourceNode.end - 1; // Skip the closing quote
325
- s.overwrite(start, end, '__overrideModule__' + sourceNode.value);
326
- }
327
- }
328
- };
329
- if (node.type === 'ImportDeclaration') {
330
- replaceIfMatch(node.source);
331
- }
332
- if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
333
- replaceIfMatch(node.source);
334
- }
335
- if (node.type === 'ImportExpression') {
336
- replaceIfMatch(node.source);
337
- }
338
- if (node.type === 'CallExpression' && node.callee.name === 'require' && node.arguments.length && node.arguments[0].type === 'Literal') {
339
- replaceIfMatch(node.arguments[0]);
340
- }
341
- }
342
- });
343
- return {
344
- code: s.toString(),
345
- map: s.generateMap({
346
- hires: true
347
- })
348
- };
349
- }
248
+ `).join(",")}
350
249
  }
351
- };
250
+ `);
352
251
  }
353
-
354
- const emptyPath = require.resolve('an-empty-js-file');
355
- const filter = createFilter();
356
- let command = '';
357
- function wrapRemoteEntry() {
358
- return `
359
- import {init, get} from "__mf__cwdRemoteEntry"
360
- export {init, get}
361
- `;
252
+ /**
253
+ * generate loadShare virtual module
254
+ */
255
+ const cacheMap1 = {};
256
+ function getLoadShareModulePath(pkg) {
257
+ const {
258
+ name
259
+ } = getNormalizeModuleFederationOptions();
260
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + `__mf__loadShare_${npmPackageNameToFileName(pkg)}.js`;
261
+ const filename = cacheMap1[pkg];
262
+ return resolve(emptyNpmDir, filename);
362
263
  }
363
- function wrapHostInit() {
364
- return `
365
- import {init} from "__mf__cwdRemoteEntry"
366
- init()
367
- `;
264
+ function writeLoadShareModule(pkg, shareItem, command) {
265
+ writeFileSync(getLoadShareModulePath(pkg), `
266
+ const {loadShare} = require("@module-federation/runtime")
267
+ const res = loadShare(${JSON.stringify(pkg)}, {
268
+ customShareInfo: {shareConfig:{
269
+ singleton: ${shareItem.shareConfig.singleton},
270
+ strictVersion: ${shareItem.shareConfig.strictVersion},
271
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)}
272
+ }}})
273
+ const exportModule = ${command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await "}res.then(factory => factory())
274
+ module.exports = exportModule
275
+ `);
276
+ }
277
+ function npmPackageNameToFileName(packageName) {
278
+ // 1. 去掉包名前的 "@"
279
+ // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
280
+ // 3. 去掉不合法的文件名字符
281
+ return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
282
+ .replace(/\//g, '__') // 将 "/" 替换为 "__"
283
+ .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
368
284
  }
285
+
286
+ const emptyPath = require.resolve('an-empty-js-file');
287
+ const REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
369
288
  function generateRemoteEntry(options) {
370
289
  const pluginImportNames = options.runtimePlugins.map((p, i) => [`$runtimePlugin_${i}`, `import $runtimePlugin_${i} from "${p}";`]);
371
290
  return `
@@ -389,6 +308,7 @@ function generateRemoteEntry(options) {
389
308
  `;
390
309
  }).join(',')}
391
310
  }
311
+ import localSharedImportMap from "${getLocalSharedImportMapId()}"
392
312
  async function init(shared = {}) {
393
313
  const localShared = {
394
314
  ${Object.keys(options.shared).map(key => {
@@ -402,9 +322,10 @@ function generateRemoteEntry(options) {
402
322
  from: ${JSON.stringify(options.name)},
403
323
  async get () {
404
324
  localShared[${JSON.stringify(key)}].loaded = true
405
- const pkg = await import(${JSON.stringify(key)})
325
+ const {${JSON.stringify(key)}: pkgDynamicImport} = localSharedImportMap
326
+ const res = await pkgDynamicImport()
406
327
  return function () {
407
- return pkg
328
+ return res
408
329
  }
409
330
  },
410
331
  shareConfig: {
@@ -446,33 +367,56 @@ function generateRemoteEntry(options) {
446
367
  }
447
368
  `;
448
369
  }
449
- function wrapShare(id, shared) {
450
- const shareConfig = shared[id].shareConfig;
370
+ const WRAP_REMOTE_ENTRY_PATH = emptyPath + '?__mf__wrapRemoteEntry__';
371
+ function generateWrapRemoteEntry() {
372
+ return `
373
+ import {init, get} from "${REMOTE_ENTRY_ID}"
374
+ export {init, get}
375
+ `;
376
+ }
377
+ /**
378
+ * Inject entry file, automatically init when used as host,
379
+ * and will not inject remoteEntry
380
+ */
381
+ const HOST_AUTO_INIT = emptyPath + '?__mf__isHostInit';
382
+ function generateWrapHostInit() {
383
+ return `
384
+ import {init} from "${REMOTE_ENTRY_ID}"
385
+ init()
386
+ `;
387
+ }
388
+
389
+ const filter$1 = createFilter();
390
+ function pluginProxyRemoteEntry () {
451
391
  return {
452
- code: `
453
- import {loadShare} from "@module-federation/runtime"
454
- const res = await loadShare(${JSON.stringify(id)}, {
455
- customShareInfo: {shareConfig:{
456
- singleton: ${shareConfig.singleton},
457
- strictVersion: ${JSON.stringify(shareConfig.strictVersion)},
458
- requiredVersion: ${JSON.stringify(shareConfig.requiredVersion)}
459
- }}})
460
- const exportModule = res()
461
- ${command === "build" && `
462
- export default 'default' in (exportModule || {}) ? exportModule.default : exportModule
463
- export const __mf__dynamicExports = exportModule
464
- ` || ""}
465
- ${command !== "build" && `
466
- export default exportModule
467
- ` || ""}
468
- `,
469
- map: null,
470
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
471
- syntheticNamedExports: '__mf__dynamicExports'
392
+ name: 'proxyRemoteEntry',
393
+ enforce: 'post',
394
+ resolveId(id) {
395
+ if (id === REMOTE_ENTRY_ID) {
396
+ return REMOTE_ENTRY_ID;
397
+ }
398
+ },
399
+ load(id) {
400
+ if (id === REMOTE_ENTRY_ID) {
401
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
402
+ }
403
+ },
404
+ async transform(code, id) {
405
+ if (!filter$1(id)) return;
406
+ if (id === REMOTE_ENTRY_ID) {
407
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
408
+ }
409
+ if (id.includes(WRAP_REMOTE_ENTRY_PATH)) {
410
+ return generateWrapRemoteEntry();
411
+ }
412
+ if (id.includes(HOST_AUTO_INIT)) {
413
+ return generateWrapHostInit();
414
+ }
415
+ }
472
416
  };
473
417
  }
474
- let con;
475
- function wrapRemote(id) {
418
+
419
+ function generateRemotes(id, command) {
476
420
  return {
477
421
  code: `
478
422
  import {loadRemote} from "@module-federation/runtime"
@@ -490,43 +434,252 @@ function wrapRemote(id) {
490
434
  syntheticNamedExports: '__mf__dynamicExports'
491
435
  };
492
436
  }
437
+
438
+ const filter = createFilter();
439
+ function pluginProxyRemotes (options) {
440
+ let command;
441
+ const {
442
+ remotes
443
+ } = options;
444
+ const matchRemotesList = Object.keys(remotes).map(item => item.replace(/\//g, "_"));
445
+ return {
446
+ name: "proxyRemotes",
447
+ config(config, {
448
+ command: _command
449
+ }) {
450
+ command = _command;
451
+ Object.keys(remotes).forEach(key => {
452
+ const remote = remotes[key];
453
+ config.resolve.alias.push({
454
+ find: new RegExp(`(${remote.name}(\/.*|$)?)`),
455
+ replacement: '$1',
456
+ customResolver(source) {
457
+ if (!config.optimizeDeps) config.optimizeDeps = {};
458
+ if (!config.optimizeDeps.needsInterop) config.optimizeDeps.needsInterop = [];
459
+ if (config.optimizeDeps.needsInterop.indexOf(source) === -1) config.optimizeDeps.needsInterop.push(source);
460
+ return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
461
+ }
462
+ });
463
+ });
464
+ },
465
+ async transform(code, id) {
466
+ if (!filter(id)) return;
467
+ let [devRemoteModuleName] = matchRemotesList.length && id.match(new RegExp(`\/(${matchRemotesList.join('|')})(\_.*\.js|\.js)`)) || [];
468
+ if (devRemoteModuleName) {
469
+ return generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command);
470
+ }
471
+ let [prodRemoteName] = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [];
472
+ if (prodRemoteName) {
473
+ return generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command);
474
+ }
475
+ }
476
+ };
477
+ }
478
+
479
+ function proxySharedModule(options) {
480
+ let {
481
+ shared = {},
482
+ include,
483
+ exclude
484
+ } = options;
485
+ const filterFunction = createFilter(include, exclude);
486
+ writeLocalSharedImportMap(Object.keys(shared));
487
+ return [{
488
+ name: 'preBuildShared',
489
+ enforce: 'post',
490
+ config(config, {
491
+ command
492
+ }) {
493
+ // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
494
+ // config.optimizeDeps.needsInterop.push('an-empty-js-file');
495
+ config.resolve.alias.push(...Object.keys(shared).map(key => {
496
+ var _config$optimizeDeps;
497
+ config == null || (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
498
+ // write proxyFile
499
+ writeLoadShareModule(key, shared[key], command);
500
+ const preBuildLibPath = getLoadShareModulePath(key);
501
+ return {
502
+ // Intercept all dependency requests to the proxy module
503
+ // Dependency requests issued by localSharedImportMap are allowed without proxying.
504
+ find: new RegExp(`^${key}$`),
505
+ replacement: preBuildLibPath,
506
+ customResolver(source, importer) {
507
+ if (importer.includes(`node_modules/${key}/`)) {
508
+ return this.resolve(key);
509
+ }
510
+ return this.resolve(preBuildLibPath);
511
+ }
512
+ };
513
+ }));
514
+ config.resolve.alias.push(...Object.keys(shared).map(key => {
515
+ return {
516
+ find: new RegExp(`^${getPreBuildLibPath(key)}$`),
517
+ customResolver(source, importer) {
518
+ return this.resolve(key);
519
+ }
520
+ };
521
+ }));
522
+ }
523
+ }, {
524
+ name: "prebuild-top-level-await",
525
+ apply: "serve",
526
+ transform(code, id) {
527
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
528
+ return null;
529
+ }
530
+ if (!filterFunction(id)) return null;
531
+ let ast;
532
+ try {
533
+ ast = this.parse(code, {
534
+ allowReturnOutsideFunction: true
535
+ });
536
+ } catch (e) {
537
+ throw new Error(`${id}: ${e}`);
538
+ }
539
+ const magicString = new MagicString(code);
540
+ walk(ast, {
541
+ enter(node) {
542
+ // 处理命名导出
543
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
544
+ const exportSpecifiers = node.specifiers.map(specifier => specifier.exported.name);
545
+ const proxyStatements = exportSpecifiers.map(name => `
546
+ const __mfproxy__await${name} = await ${name}();
547
+ const __mfproxy__${name} = () => __mfproxy__await${name};
548
+ `).join('\n');
549
+ const exportStatements = exportSpecifiers.map(name => `__mfproxy__${name} as ${name}`).join(', ');
550
+ const start = node.start;
551
+ const end = node.end;
552
+ const replacement = `${proxyStatements}\nexport { ${exportStatements} };`;
553
+ magicString.overwrite(start, end, replacement);
554
+ }
555
+ // 处理默认导出
556
+ if (node.type === 'ExportDefaultDeclaration') {
557
+ const declaration = node.declaration;
558
+ const start = node.start;
559
+ const end = node.end;
560
+ let proxyStatement;
561
+ let exportStatement = 'default';
562
+ if (declaration.type === 'Identifier') {
563
+ // 处理标识符 (如: export default foo;)
564
+ proxyStatement = `
565
+ const __mfproxy__awaitdefault = await ${declaration.name}();
566
+ const __mfproxy__default = __mfproxy__awaitdefault;
567
+ `;
568
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
569
+ // 处理调用表达式或函数声明 (如: export default someFunction();)
570
+ const declarationCode = code.slice(declaration.start, declaration.end);
571
+ proxyStatement = `
572
+ const __mfproxy__awaitdefault = await (${declarationCode});
573
+ const __mfproxy__default = __mfproxy__awaitdefault;
574
+ `;
575
+ } else {
576
+ // 其他类型 (可以根据需要添加更多处理逻辑)
577
+ proxyStatement = `
578
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
579
+ const __mfproxy__default = __mfproxy__awaitdefault;
580
+ `;
581
+ }
582
+ const replacement = `${proxyStatement}\nexport { __mfproxy__default as ${exportStatement} };`;
583
+ magicString.overwrite(start, end, replacement);
584
+ }
585
+ }
586
+ });
587
+ return {
588
+ code: magicString.toString(),
589
+ map: magicString.generateMap({
590
+ hires: true
591
+ })
592
+ };
593
+ }
594
+ }];
595
+ }
596
+
597
+ var aliasToArrayPlugin = {
598
+ name: 'alias-transform-plugin',
599
+ config: (config, {
600
+ command
601
+ }) => {
602
+ if (!config.resolve) config.resolve = {};
603
+ if (!config.resolve.alias) config.resolve.alias = [];
604
+ const {
605
+ alias
606
+ } = config.resolve;
607
+ if (typeof alias === 'object' && !Array.isArray(alias)) {
608
+ config.resolve.alias = Object.entries(alias).map(([find, replacement]) => ({
609
+ find,
610
+ replacement
611
+ }));
612
+ }
613
+ }
614
+ };
615
+
616
+ var normalizeBuildPlugin = (singleChunkModules => ({
617
+ name: 'normalizeBuild',
618
+ config: (config, {
619
+ command
620
+ }) => {
621
+ if (!config.build) config.build = {};
622
+ if (!config.build.rollupOptions) config.build.rollupOptions = {};
623
+ let {
624
+ rollupOptions
625
+ } = config.build;
626
+ if (!rollupOptions.output) rollupOptions.output = {};
627
+ normalizeManualChunks(rollupOptions.output, singleChunkModules);
628
+ }
629
+ }));
630
+ function normalizeManualChunks(output, singleChunkModules) {
631
+ const pattern = new RegExp(`node_modules/(${singleChunkModules.join('|')})/`);
632
+ if (!output.manualChunks) output.manualChunks = {};
633
+ const wrapManualChunks = original => (id, ...args) => {
634
+ const [_, moduleName] = id.match(pattern) || [];
635
+ if (moduleName) {
636
+ return moduleName;
637
+ }
638
+ if (typeof original === 'function') {
639
+ return original(id, ...args);
640
+ }
641
+ if (typeof original === 'object' && original) {
642
+ return original[id];
643
+ }
644
+ };
645
+ output.manualChunks = wrapManualChunks(output.manualChunks);
646
+ }
647
+
648
+ var normalizeOptimizeDepsPlugin = {
649
+ name: 'normalizeOptimizeDeps',
650
+ config: (config, {
651
+ command
652
+ }) => {
653
+ let {
654
+ optimizeDeps
655
+ } = config;
656
+ if (!optimizeDeps) {
657
+ config.optimizeDeps = {};
658
+ optimizeDeps = config.optimizeDeps;
659
+ }
660
+ if (!optimizeDeps.include) optimizeDeps.include = [];
661
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
662
+ }
663
+ };
664
+
493
665
  function federation(mfUserOptions) {
494
666
  const options = normalizeModuleFederationOptions(mfUserOptions);
495
667
  const {
668
+ name,
496
669
  remotes,
497
670
  shared,
498
671
  filename
499
672
  } = options;
500
- const alias = [{
501
- find: '@module-federation/runtime',
502
- replacement: require.resolve('@module-federation/runtime')
503
- }];
504
- Object.keys(remotes).forEach(key => {
505
- const remote = remotes[key];
506
- alias.push({
507
- find: new RegExp(`(${remote.name}(\/.*|$)?)`),
508
- replacement: '$1',
509
- customResolver(source) {
510
- if (!con.optimizeDeps) con.optimizeDeps = {};
511
- if (!con.optimizeDeps.needsInterop) con.optimizeDeps.needsInterop = [];
512
- if (con.optimizeDeps.needsInterop.indexOf(source) === -1) con.optimizeDeps.needsInterop.push(source);
513
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
514
- }
515
- });
516
- });
517
- const remotePrefixList = Object.keys(remotes);
518
- // pkgname will be escaped, and matching path also needs to be processed in the same way:
519
- // @json2csv/plainjs --> .vite/deps/@json2csv_plainjs
520
- const sharedKeyMatchList = Object.keys(shared).map(item => `__overrideModule__${item.replace('/', '_')}`);
673
+ if (!name) throw new Error("name is required");
521
674
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([...Object.keys(shared), "@module-federation/runtime"]), ...addEntry({
522
675
  entryName: 'remoteEntry',
523
- entryPath: emptyPath + '?__mf__wrapRemoteEntry__',
676
+ entryPath: WRAP_REMOTE_ENTRY_PATH,
524
677
  fileName: filename
525
678
  }), ...addEntry({
526
679
  entryName: 'hostInit',
527
- entryPath: emptyPath + '?__mf__isHostInit'
528
- }), overrideModule({
529
- override: Object.keys(shared)
680
+ entryPath: HOST_AUTO_INIT
681
+ }), pluginProxyRemoteEntry(), pluginProxyRemotes(options), ...proxySharedModule({
682
+ shared
530
683
  }), {
531
684
  name: 'module-federation-vite',
532
685
  enforce: 'post',
@@ -534,55 +687,14 @@ function federation(mfUserOptions) {
534
687
  command: _command
535
688
  }) {
536
689
  var _config$optimizeDeps;
537
- con = config;
538
- command = _command;
539
- config.resolve.alias.push(...alias);
540
- (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
541
- Object.keys(shared).forEach(key => {
542
- var _config$optimizeDeps2;
543
- (_config$optimizeDeps2 = config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(key);
690
+ config.resolve.alias.push({
691
+ find: '@module-federation/runtime',
692
+ replacement: require.resolve('@module-federation/runtime')
544
693
  });
545
- },
546
- resolveId(id) {
547
- if (id === '__mf__cwdRemoteEntry') {
548
- return '__mf__cwdRemoteEntry';
549
- }
550
- },
551
- load(id) {
552
- if (id === '__mf__cwdRemoteEntry') {
553
- return generateRemoteEntry(options);
554
- }
555
- },
556
- async transform(code, id) {
557
- if (!filter(id)) return;
558
- if (id === '__mf__cwdRemoteEntry') {
559
- return generateRemoteEntry(options);
560
- }
561
- if (id.indexOf('__mf__wrapRemoteEntry__') > -1) {
562
- return wrapRemoteEntry();
563
- }
564
- if (id.indexOf('__mf__isHostInit') > -1) {
565
- return wrapHostInit();
566
- }
567
- if (id.indexOf('__mf__cwdRemoteEntry') > -1) {
568
- return generateRemoteEntry(options);
569
- }
570
- let [devSharedModuleName] = sharedKeyMatchList.length && id.match(new RegExp(`\/(${sharedKeyMatchList.join('|')})(\_.*\.js|\.js)`)) || [];
571
- if (devSharedModuleName) {
572
- return wrapShare(devSharedModuleName.replace('/__overrideModule__', '').replace(/_/g, '/').replace('.js', ''), shared);
573
- }
574
- let [prodSharedName] = id.match(/\_\_overrideModule\_\_=[^&]+/) || [];
575
- if (prodSharedName) {
576
- return wrapShare(decodeURIComponent(prodSharedName.replace('__overrideModule__=', '')), shared);
577
- }
578
- let [devRemoteModuleName] = remotePrefixList.length && id.match(new RegExp(`\/(${remotePrefixList.join('|')})(\_.*\.js|\.js)`)) || [];
579
- if (devRemoteModuleName) {
580
- return wrapRemote(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''));
581
- }
582
- let [prodRemoteName] = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [];
583
- if (prodRemoteName) {
584
- return wrapRemote(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')));
585
- }
694
+ (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
695
+ // Object.keys(shared).forEach((key) => {
696
+ // config.optimizeDeps?.include?.push(key);
697
+ // });
586
698
  }
587
699
  }];
588
700
  }