@module-federation/vite 1.0.0 → 1.1.1

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/lib/index.esm.js CHANGED
@@ -11,13 +11,13 @@ var addEntry = function addEntry(_ref) {
11
11
  var entryName = _ref.entryName,
12
12
  entryPath = _ref.entryPath,
13
13
  fileName = _ref.fileName;
14
- var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
14
+ var devEntryPath = entryPath.startsWith('virtual:mf') ? '/@id/' + entryPath : entryPath;
15
15
  var entryFiles = [];
16
16
  var htmlFilePath;
17
17
  var _command;
18
18
  return [{
19
19
  name: 'add-entry',
20
- apply: "serve",
20
+ apply: 'serve',
21
21
  config: function config(_config, _ref2) {
22
22
  var command = _ref2.command;
23
23
  _command = command;
@@ -43,8 +43,8 @@ var addEntry = function addEntry(_ref) {
43
43
  return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
44
44
  }
45
45
  }, {
46
- name: "add-entry",
47
- enforce: "post",
46
+ name: 'add-entry',
47
+ enforce: 'post',
48
48
  configResolved: function configResolved(config) {
49
49
  var inputOptions = config.build.rollupOptions.input;
50
50
  if (!inputOptions) {
@@ -61,8 +61,8 @@ var addEntry = function addEntry(_ref) {
61
61
  }
62
62
  },
63
63
  buildStart: function buildStart() {
64
- if (_command === "serve") return;
65
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
64
+ if (_command === 'serve') return;
65
+ var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
66
66
  var emitFileOptions = {
67
67
  name: entryName,
68
68
  type: 'chunk',
@@ -99,10 +99,10 @@ var addEntry = function addEntry(_ref) {
99
99
  function PluginDevProxyModuleTopLevelAwait() {
100
100
  var filterFunction = createFilter();
101
101
  return {
102
- name: "dev-proxy-module-top-level-await",
103
- apply: "serve",
102
+ name: 'dev-proxy-module-top-level-await',
103
+ apply: 'serve',
104
104
  transform: function transform(code, id) {
105
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
105
+ if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
106
106
  return null;
107
107
  }
108
108
  if (!filterFunction(id)) return null;
@@ -186,6 +186,15 @@ function _createForOfIteratorHelperLoose(r, e) {
186
186
  }
187
187
  throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
188
188
  }
189
+ function _extends() {
190
+ return _extends = Object.assign ? Object.assign.bind() : function (n) {
191
+ for (var e = 1; e < arguments.length; e++) {
192
+ var t = arguments[e];
193
+ for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
194
+ }
195
+ return n;
196
+ }, _extends.apply(null, arguments);
197
+ }
189
198
  function _unsupportedIterableToArray(r, a) {
190
199
  if (r) {
191
200
  if ("string" == typeof r) return _arrayLikeToArray(r, a);
@@ -194,6 +203,12 @@ function _unsupportedIterableToArray(r, a) {
194
203
  }
195
204
  }
196
205
 
206
+ var warn = function warn(message) {
207
+ return message.split('\n').forEach(function (msg) {
208
+ return console.warn('\x1b[33m%s\x1b[0m', msg);
209
+ });
210
+ };
211
+
197
212
  function normalizeExposesItem(key, item) {
198
213
  var importPath = '';
199
214
  if (typeof item === 'string') {
@@ -267,7 +282,7 @@ function normalizeShareItem(key, shareItem) {
267
282
  from: '',
268
283
  shareConfig: {
269
284
  singleton: false,
270
- requiredVersion: "^" + version || '*'
285
+ requiredVersion: version ? "^" + version : '*'
271
286
  }
272
287
  };
273
288
  }
@@ -278,7 +293,7 @@ function normalizeShareItem(key, shareItem) {
278
293
  scope: shareItem.shareScope || 'default',
279
294
  shareConfig: {
280
295
  singleton: shareItem.singleton || false,
281
- requiredVersion: shareItem.requiredVersion || "^" + version || '*',
296
+ requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
282
297
  strictVersion: !!shareItem.strictVersion
283
298
  }
284
299
  };
@@ -307,13 +322,13 @@ function normalizeManifest(manifest) {
307
322
  if (manifest === void 0) {
308
323
  manifest = false;
309
324
  }
310
- if (typeof manifest === "boolean") {
325
+ if (typeof manifest === 'boolean') {
311
326
  return manifest;
312
327
  }
313
328
  return Object.assign({
314
- filePath: "",
329
+ filePath: '',
315
330
  disableAssetsAnalyze: false,
316
- fileName: "mf-manifest.json"
331
+ fileName: 'mf-manifest.json'
317
332
  }, manifest);
318
333
  }
319
334
  var config;
@@ -322,10 +337,13 @@ function getNormalizeModuleFederationOptions() {
322
337
  }
323
338
  function getNormalizeShareItem(key) {
324
339
  var options = getNormalizeModuleFederationOptions();
325
- var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
340
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
326
341
  return shareItem;
327
342
  }
328
343
  function normalizeModuleFederationOptions(options) {
344
+ if (options.getPublicPath) {
345
+ warn("We are ignoring the getPublicPath options because they are natively supported by Vite\nwith the \"experimental.renderBuiltUrl\" configuration https://vitejs.dev/guide/build#advanced-base-options");
346
+ }
329
347
  return config = {
330
348
  exposes: normalizeExposes(options.exposes),
331
349
  filename: options.filename || 'remoteEntry-[hash]',
@@ -337,11 +355,12 @@ function normalizeModuleFederationOptions(options) {
337
355
  shareScope: options.shareScope || 'default',
338
356
  shared: normalizeShared(options.shared),
339
357
  runtimePlugins: options.runtimePlugins || [],
340
- getPublicPath: options.getPublicPath,
341
358
  implementation: options.implementation,
342
359
  manifest: normalizeManifest(options.manifest),
343
360
  dev: options.dev,
344
- dts: options.dts
361
+ dts: options.dts,
362
+ getPublicPath: options.getPublicPath,
363
+ shareStrategy: options.shareStrategy
345
364
  };
346
365
  }
347
366
 
@@ -359,8 +378,8 @@ function normalizeModuleFederationOptions(options) {
359
378
  * @returns {string} - The encoded file name.
360
379
  */
361
380
  function packageNameEncode(name) {
362
- if (typeof name !== "string") throw new Error("A string package name is required");
363
- return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
381
+ if (typeof name !== 'string') throw new Error('A string package name is required');
382
+ return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
364
383
  }
365
384
  /**
366
385
  * Decodes an encoded file name back to the original package name.
@@ -368,8 +387,8 @@ function packageNameEncode(name) {
368
387
  * @returns {string} - The decoded package name.
369
388
  */
370
389
  function packageNameDecode(encoded) {
371
- if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
372
- return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
390
+ if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
391
+ return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
373
392
  }
374
393
 
375
394
  /**
@@ -378,11 +397,11 @@ function packageNameDecode(encoded) {
378
397
  function getLocalSharedImportMapPath_temp() {
379
398
  var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
380
399
  name = _getNormalizeModuleFe.name;
381
- return path__default.resolve(".__mf__temp", packageNameEncode(name), "localSharedImportMap");
400
+ return path__default.resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
382
401
  }
383
402
  function writeLocalSharedImportMap_temp(content) {
384
403
  var localSharedImportMapId = getLocalSharedImportMapPath_temp();
385
- createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
404
+ createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
386
405
  }
387
406
  function createFile(filePath, content) {
388
407
  var dir = path__default.dirname(filePath);
@@ -404,16 +423,16 @@ var nodeModulesDir = function findNodeModulesDir(startDir) {
404
423
  }
405
424
  currentDir = dirname(currentDir);
406
425
  }
407
- return "";
426
+ return '';
408
427
  }();
409
- var virtualPackageName = "__mf__virtual";
428
+ var virtualPackageName = '__mf__virtual';
410
429
  if (!existsSync(resolve(nodeModulesDir, virtualPackageName))) {
411
430
  mkdirSync(resolve(nodeModulesDir, virtualPackageName));
412
431
  }
413
- writeFileSync(resolve(nodeModulesDir, virtualPackageName, "empty.js"), "");
414
- writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.stringify({
432
+ writeFileSync(resolve(nodeModulesDir, virtualPackageName, 'empty.js'), '');
433
+ writeFileSync(resolve(nodeModulesDir, virtualPackageName, 'package.json'), JSON.stringify({
415
434
  name: virtualPackageName,
416
- main: "empty.js"
435
+ main: 'empty.js'
417
436
  }));
418
437
  var patternMap = {};
419
438
  var cacheMap = {};
@@ -427,7 +446,7 @@ var VirtualModule = /*#__PURE__*/function () {
427
446
  tag = '__mf_v__';
428
447
  }
429
448
  if (suffix === void 0) {
430
- suffix = "";
449
+ suffix = '';
431
450
  }
432
451
  this.name = void 0;
433
452
  this.tag = void 0;
@@ -435,13 +454,13 @@ var VirtualModule = /*#__PURE__*/function () {
435
454
  this.inited = false;
436
455
  this.name = name;
437
456
  this.tag = tag;
438
- this.suffix = suffix || ((_name$split$slice$pop = name.split(".").slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, ".$1")) || ".js";
457
+ this.suffix = suffix || ((_name$split$slice$pop = name.split('.').slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, '.$1')) || '.js';
439
458
  if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
440
459
  cacheMap[this.tag][this.name] = this;
441
460
  }
442
461
  VirtualModule.findModule = function findModule(tag, str) {
443
462
  if (str === void 0) {
444
- str = "";
463
+ str = '';
445
464
  }
446
465
  if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
447
466
  var moduleName = (str.match(patternMap[tag]) || [])[2];
@@ -470,16 +489,24 @@ var VirtualModule = /*#__PURE__*/function () {
470
489
  return VirtualModule;
471
490
  }();
472
491
 
473
- var virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
492
+ var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
493
+ function generateExposes() {
494
+ var options = getNormalizeModuleFederationOptions();
495
+ return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
496
+ return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
497
+ }).join(',') + "\n }\n ";
498
+ }
499
+
500
+ var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
474
501
  function writeRuntimeInitStatus() {
475
- virtualRuntimeInitStatus.writeSync("\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n export {\n initPromise,\n initResolve,\n initReject\n }\n ");
502
+ virtualRuntimeInitStatus.writeSync("\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n module.exports = {\n initPromise,\n initResolve,\n initReject\n }\n ");
476
503
  }
477
504
 
478
505
  var cacheRemoteMap = {};
479
506
  var LOAD_REMOTE_TAG = '__loadRemote__';
480
507
  function getRemoteVirtualModule(remote, command) {
481
508
  if (!cacheRemoteMap[remote]) {
482
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
509
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
483
510
  cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
484
511
  }
485
512
  var virtual = cacheRemoteMap[remote];
@@ -496,7 +523,7 @@ function getUsedRemotesMap() {
496
523
  return usedRemotesMap;
497
524
  }
498
525
  function generateRemotes(id, command) {
499
- return "\n const {loadRemote} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
526
+ return "\n const {loadRemote} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
500
527
  }
501
528
 
502
529
  /**
@@ -506,10 +533,10 @@ function generateRemotes(id, command) {
506
533
  */
507
534
  // *** __prebuild__
508
535
  var preBuildCacheMap = {};
509
- var PREBUILD_TAG = "__prebuild__";
536
+ var PREBUILD_TAG = '__prebuild__';
510
537
  function writePreBuildLibPath(pkg) {
511
538
  if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
512
- preBuildCacheMap[pkg].writeSync("");
539
+ preBuildCacheMap[pkg].writeSync('');
513
540
  }
514
541
  function getPreBuildLibImportId(pkg) {
515
542
  if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
@@ -517,15 +544,15 @@ function getPreBuildLibImportId(pkg) {
517
544
  return importId;
518
545
  }
519
546
  // *** __loadShare__
520
- var LOAD_SHARE_TAG = "__loadShare__";
547
+ var LOAD_SHARE_TAG = '__loadShare__';
521
548
  var loadShareCacheMap = {};
522
549
  function getLoadShareModulePath(pkg) {
523
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
550
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
524
551
  var filepath = loadShareCacheMap[pkg].getPath();
525
552
  return filepath;
526
553
  }
527
554
  function writeLoadShareModule(pkg, shareItem, command) {
528
- loadShareCacheMap[pkg].writeSync("\n \n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== "build" ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {loadShare} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}}))\n const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "res.then(factory => factory())\n module.exports = exportModule\n ");
555
+ loadShareCacheMap[pkg].writeSync("\n \n ;() => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== 'build' ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {loadShare} = require(\"@module-federation/runtime\")\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(_ => loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}}))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "res.then(factory => factory())\n module.exports = exportModule\n ");
529
556
  }
530
557
 
531
558
  var usedShares = new Set();
@@ -536,7 +563,7 @@ function addUsedShares(pkg) {
536
563
  usedShares.add(pkg);
537
564
  }
538
565
  // *** Expose locally provided shared modules here
539
- new VirtualModule("localSharedImportMap");
566
+ new VirtualModule('localSharedImportMap');
540
567
  function getLocalSharedImportMapPath() {
541
568
  return getLocalSharedImportMapPath_temp();
542
569
  // return localSharedImportMapModule.getPath()
@@ -554,7 +581,7 @@ function generateLocalSharedImportMap() {
554
581
  var options = getNormalizeModuleFederationOptions();
555
582
  return "\n const importMap = {\n " + Array.from(getUsedShares()).map(function (pkg) {
556
583
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
557
- }).join(",") + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
584
+ }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).map(function (key) {
558
585
  var shareItem = getNormalizeShareItem(key);
559
586
  return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap \n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
560
587
  }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
@@ -569,17 +596,15 @@ function generateRemoteEntry(options) {
569
596
  });
570
597
  return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
571
598
  return item[1];
572
- }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
573
- return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
574
- }).join(',') + "\n }\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
599
+ }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
575
600
  return item[0] + "()";
576
- }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
601
+ }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: " + options.shareStrategy : '') + "\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
577
602
  }
578
603
  /**
579
604
  * Inject entry file, automatically init when used as host,
580
605
  * and will not inject remoteEntry
581
606
  */
582
- var hostAutoInitModule = new VirtualModule("hostAutoInit");
607
+ var hostAutoInitModule = new VirtualModule('hostAutoInit');
583
608
  function writeHostAutoInit() {
584
609
  hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
585
610
  }
@@ -600,13 +625,14 @@ var Manifest = function Manifest() {
600
625
  var mfOptions = getNormalizeModuleFederationOptions();
601
626
  var name = mfOptions.name,
602
627
  filename = mfOptions.filename,
628
+ getPublicPath = mfOptions.getPublicPath,
603
629
  manifestOptions = mfOptions.manifest;
604
- var mfManifestName = "";
630
+ var mfManifestName = '';
605
631
  if (manifestOptions === true) {
606
- mfManifestName = "mf-manifest.json";
632
+ mfManifestName = 'mf-manifest.json';
607
633
  }
608
- if (typeof manifestOptions !== "boolean") {
609
- mfManifestName = join((manifestOptions == null ? void 0 : manifestOptions.filePath) || "", (manifestOptions == null ? void 0 : manifestOptions.fileName) || "");
634
+ if (typeof manifestOptions !== 'boolean') {
635
+ mfManifestName = join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
610
636
  }
611
637
  var extensions;
612
638
  var root;
@@ -614,7 +640,7 @@ var Manifest = function Manifest() {
614
640
  var publicPath;
615
641
  var _command;
616
642
  return [{
617
- name: 'moddule-federation-manifest',
643
+ name: 'module-federation-manifest',
618
644
  apply: 'serve',
619
645
  configureServer: function configureServer(server) {
620
646
  server.middlewares.use(function (req, res, next) {
@@ -622,10 +648,10 @@ var Manifest = function Manifest() {
622
648
  next();
623
649
  return;
624
650
  }
625
- if (req.url === mfManifestName.replace(/^\/?/, "/")) {
651
+ if (req.url === mfManifestName.replace(/^\/?/, '/')) {
626
652
  res.setHeader('Content-Type', 'application/json');
627
653
  res.setHeader('Access-Control-Allow-Origin', '*');
628
- res.end(JSON.stringify({
654
+ res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
629
655
  id: name,
630
656
  name: name,
631
657
  metaData: {
@@ -652,68 +678,15 @@ var Manifest = function Manifest() {
652
678
  globalName: name,
653
679
  pluginVersion: '0.2.5',
654
680
  publicPath: publicPath
655
- },
656
- shared: Array.from(getUsedShares()).map(function (shareKey) {
657
- var shareItem = getNormalizeShareItem(shareKey);
658
- return {
659
- id: name + ":" + shareKey,
660
- name: shareKey,
661
- version: shareItem.version,
662
- requiredVersion: shareItem.shareConfig.requiredVersion,
663
- assets: {
664
- js: {
665
- async: [],
666
- sync: []
667
- },
668
- css: {
669
- async: [],
670
- sync: []
671
- }
672
- }
673
- };
674
- }),
675
- remotes: function () {
676
- var remotes = [];
677
- var usedRemotesMap = getUsedRemotesMap();
678
- Object.keys(usedRemotesMap).forEach(function (remoteKey) {
679
- var usedModules = Array.from(usedRemotesMap[remoteKey]);
680
- usedModules.forEach(function (moduleKey) {
681
- remotes.push({
682
- federationContainerName: mfOptions.remotes[remoteKey].entry,
683
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
684
- alias: remoteKey,
685
- entry: '*'
686
- });
687
- });
688
- });
689
- return remotes;
690
- }(),
691
- exposes: Object.keys(mfOptions.exposes).map(function (key) {
692
- var formatKey = key.replace('./', '');
693
- return {
694
- id: name + ':' + formatKey,
695
- name: formatKey,
696
- assets: {
697
- js: {
698
- async: [],
699
- sync: []
700
- },
701
- css: {
702
- sync: [],
703
- async: []
704
- }
705
- },
706
- path: key
707
- };
708
- })
709
- }));
681
+ }
682
+ })));
710
683
  } else {
711
684
  next();
712
685
  }
713
686
  });
714
687
  }
715
688
  }, {
716
- name: 'moddule-federation-manifest',
689
+ name: 'module-federation-manifest',
717
690
  enforce: 'post',
718
691
  config: function config(_config, _ref) {
719
692
  var command = _ref.command;
@@ -724,10 +697,10 @@ var Manifest = function Manifest() {
724
697
  configResolved: function configResolved(config) {
725
698
  root = config.root;
726
699
  extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
727
- publicPath = config.base ? config.base.replace(/\/?$/, "/") : "auto";
728
- if (_command === "serve") {
700
+ publicPath = config.base ? config.base.replace(/\/?$/, '/') : 'auto';
701
+ if (_command === 'serve') {
729
702
  var origin = config.server.origin;
730
- publicPath = origin ? origin.replace(/\/?$/, "/") : "auto";
703
+ publicPath = origin ? origin.replace(/\/?$/, '/') : 'auto';
731
704
  }
732
705
  },
733
706
  generateBundle: function generateBundle(options, bundle) {
@@ -769,7 +742,7 @@ var Manifest = function Manifest() {
769
742
  var _Object$entries$_i = _Object$entries[_i],
770
743
  fileName = _Object$entries$_i[0],
771
744
  fileData = _Object$entries$_i[1];
772
- if (mfOptions.filename.replace(/[\[\]]/g, "_") === fileData.name || fileData.name === "remoteEntry") {
745
+ if (mfOptions.filename.replace(/[\[\]]/g, '_') === fileData.name || fileData.name === 'remoteEntry') {
773
746
  remoteEntryFile = fileData.fileName;
774
747
  }
775
748
  if (fileData.type === 'chunk') {
@@ -781,7 +754,7 @@ var Manifest = function Manifest() {
781
754
  // 检查模块是否在 preloadModules 列表中
782
755
  for (var _iterator2 = _createForOfIteratorHelperLoose(exposesModules), _step2; !(_step2 = _iterator2()).done;) {
783
756
  var preloadModule = _step2.value;
784
- var formatPreloadModule = preloadModule.replace("./", "");
757
+ var formatPreloadModule = preloadModule.replace('./', '');
785
758
  if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
786
759
  var _filesContainingModul;
787
760
  if (!filesContainingModules[preloadModule]) {
@@ -800,12 +773,11 @@ var Manifest = function Manifest() {
800
773
  }
801
774
  }
802
775
  }
803
- ;
804
776
  var fileToShareKey = {};
805
777
  return Promise.resolve(Promise.all(Array.from(getUsedShares()).map(function (shareKey) {
806
778
  try {
807
779
  return Promise.resolve(_this.resolve(getPreBuildLibImportId(shareKey))).then(function (_this$resolve) {
808
- var file = _this$resolve.id.split("?")[0];
780
+ var file = _this$resolve.id.split('?')[0];
809
781
  fileToShareKey[file] = shareKey;
810
782
  });
811
783
  } catch (e) {
@@ -845,7 +817,7 @@ var Manifest = function Manifest() {
845
817
  _this.emitFile({
846
818
  type: 'asset',
847
819
  fileName: mfManifestName,
848
- source: generateMFManifest(filesContainingModules)
820
+ source: JSON.stringify(generateMFManifest(filesContainingModules))
849
821
  });
850
822
  });
851
823
  } catch (e) {
@@ -876,8 +848,7 @@ var Manifest = function Manifest() {
876
848
  });
877
849
  // @ts-ignore
878
850
  var shared = Array.from(getUsedShares()).map(function (shareKey) {
879
- // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
880
- if (!preloadMap[shareKey]) return;
851
+ var _preloadMap$shareKey, _preloadMap$shareKey2;
881
852
  var shareItem = getNormalizeShareItem(shareKey);
882
853
  return {
883
854
  id: name + ":" + shareKey,
@@ -886,8 +857,8 @@ var Manifest = function Manifest() {
886
857
  requiredVersion: shareItem.shareConfig.requiredVersion,
887
858
  assets: {
888
859
  js: {
889
- async: preloadMap[shareKey].async,
890
- sync: preloadMap[shareKey].sync
860
+ async: (preloadMap == null || (_preloadMap$shareKey = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey.async) || [],
861
+ sync: (preloadMap == null || (_preloadMap$shareKey2 = preloadMap[shareKey]) == null ? void 0 : _preloadMap$shareKey2.sync) || []
891
862
  },
892
863
  css: {
893
864
  async: [],
@@ -899,17 +870,17 @@ var Manifest = function Manifest() {
899
870
  return item;
900
871
  });
901
872
  var exposes = Object.keys(options.exposes).map(function (key) {
873
+ var _preloadMap$sourceFil, _preloadMap$sourceFil2;
902
874
  // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
903
875
  var formatKey = key.replace('./', '');
904
876
  var sourceFile = options.exposes[key]["import"];
905
- if (!preloadMap[sourceFile]) return;
906
877
  return {
907
878
  id: name + ':' + formatKey,
908
879
  name: formatKey,
909
880
  assets: {
910
881
  js: {
911
- async: preloadMap[sourceFile].async,
912
- sync: preloadMap[sourceFile].sync
882
+ async: (preloadMap == null || (_preloadMap$sourceFil = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil.async) || [],
883
+ sync: (preloadMap == null || (_preloadMap$sourceFil2 = preloadMap[sourceFile]) == null ? void 0 : _preloadMap$sourceFil2.sync) || []
913
884
  },
914
885
  css: {
915
886
  sync: [],
@@ -924,7 +895,7 @@ var Manifest = function Manifest() {
924
895
  var result = {
925
896
  id: name,
926
897
  name: name,
927
- metaData: {
898
+ metaData: _extends({
928
899
  name: name,
929
900
  type: 'app',
930
901
  buildInfo: {
@@ -940,14 +911,17 @@ var Manifest = function Manifest() {
940
911
  // "api": "@mf-types.d.ts"
941
912
  },
942
913
  globalName: name,
943
- pluginVersion: '0.2.5',
914
+ pluginVersion: '0.2.5'
915
+ }, !!getPublicPath ? {
916
+ getPublicPath: getPublicPath
917
+ } : {
944
918
  publicPath: publicPath
945
- },
919
+ }),
946
920
  shared: shared,
947
921
  remotes: remotes,
948
922
  exposes: exposes
949
923
  };
950
- return JSON.stringify(result);
924
+ return result;
951
925
  }
952
926
  };
953
927
 
@@ -956,20 +930,21 @@ var _resolve,
956
930
  _resolve = resolve;
957
931
  });
958
932
  var parsePromise = promise;
933
+ var exposesParseEnd = false;
959
934
  var parseStartSet = new Set();
960
935
  var parseEndSet = new Set();
961
936
  function pluginModuleParseEnd (excludeFn) {
962
937
  return [{
963
- name: "_",
964
- apply: "serve",
938
+ name: '_',
939
+ apply: 'serve',
965
940
  config: function config() {
966
941
  // No waiting in development mode
967
942
  _resolve(1);
968
943
  }
969
944
  }, {
970
- enforce: "pre",
971
- name: "parseStart",
972
- apply: "build",
945
+ enforce: 'pre',
946
+ name: 'parseStart',
947
+ apply: 'build',
973
948
  load: function load(id) {
974
949
  if (excludeFn(id)) {
975
950
  return;
@@ -977,16 +952,20 @@ function pluginModuleParseEnd (excludeFn) {
977
952
  parseStartSet.add(id);
978
953
  }
979
954
  }, {
980
- enforce: "post",
981
- name: "parseEnd",
982
- apply: "build",
955
+ enforce: 'post',
956
+ name: 'parseEnd',
957
+ apply: 'build',
983
958
  moduleParsed: function moduleParsed(module) {
984
959
  var id = module.id;
985
960
  if (excludeFn(id)) {
986
961
  return;
987
962
  }
963
+ if (id === VIRTUAL_EXPOSES) {
964
+ // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
965
+ exposesParseEnd = true;
966
+ }
988
967
  parseEndSet.add(id);
989
- if (parseStartSet.size === parseEndSet.size) {
968
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
990
969
  _resolve(1);
991
970
  }
992
971
  }
@@ -1002,6 +981,9 @@ function pluginProxyRemoteEntry () {
1002
981
  if (id === REMOTE_ENTRY_ID) {
1003
982
  return REMOTE_ENTRY_ID;
1004
983
  }
984
+ if (id === VIRTUAL_EXPOSES) {
985
+ return VIRTUAL_EXPOSES;
986
+ }
1005
987
  },
1006
988
  load: function load(id) {
1007
989
  if (id === REMOTE_ENTRY_ID) {
@@ -1009,6 +991,9 @@ function pluginProxyRemoteEntry () {
1009
991
  return generateRemoteEntry(getNormalizeModuleFederationOptions());
1010
992
  });
1011
993
  }
994
+ if (id === VIRTUAL_EXPOSES) {
995
+ return generateExposes();
996
+ }
1012
997
  },
1013
998
  transform: function transform(code, id) {
1014
999
  try {
@@ -1018,6 +1003,9 @@ function pluginProxyRemoteEntry () {
1018
1003
  return generateRemoteEntry(getNormalizeModuleFederationOptions());
1019
1004
  }));
1020
1005
  }
1006
+ if (id === VIRTUAL_EXPOSES) {
1007
+ return Promise.resolve(generateExposes());
1008
+ }
1021
1009
  return Promise.resolve();
1022
1010
  } catch (e) {
1023
1011
  return Promise.reject(e);
@@ -1030,14 +1018,14 @@ createFilter();
1030
1018
  function pluginProxyRemotes (options) {
1031
1019
  var remotes = options.remotes;
1032
1020
  return {
1033
- name: "proxyRemotes",
1021
+ name: 'proxyRemotes',
1034
1022
  config: function config(_config, _ref) {
1035
1023
  var _command = _ref.command;
1036
1024
  Object.keys(remotes).forEach(function (key) {
1037
1025
  var remote = remotes[key];
1038
1026
  _config.resolve.alias.push({
1039
1027
  find: new RegExp("^(" + remote.name + "(/.*|$))"),
1040
- replacement: "$1",
1028
+ replacement: '$1',
1041
1029
  customResolver: function customResolver(source) {
1042
1030
  var remoteModule = getRemoteVirtualModule(source, _command);
1043
1031
  addUsedRemote(remote.name, source);
@@ -1091,8 +1079,8 @@ function proxySharedModule(options) {
1091
1079
  shared = _options$shared === void 0 ? {} : _options$shared;
1092
1080
  var _config;
1093
1081
  return [{
1094
- name: "generateLocalSharedImportMap",
1095
- enforce: "post",
1082
+ name: 'generateLocalSharedImportMap',
1083
+ enforce: 'post',
1096
1084
  load: function load(id) {
1097
1085
  if (id.includes(getLocalSharedImportMapPath())) {
1098
1086
  return parsePromise.then(function (_) {
@@ -1117,11 +1105,11 @@ function proxySharedModule(options) {
1117
1105
  var _config2$resolve$alia, _config2$resolve$alia2;
1118
1106
  var command = _ref.command;
1119
1107
  (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
1120
- var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
1108
+ var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
1121
1109
  return {
1122
1110
  // Intercept all shared requests and proxy them to loadShare
1123
1111
  find: new RegExp(pattern),
1124
- replacement: "$1",
1112
+ replacement: '$1',
1125
1113
  customResolver: function customResolver(source, importer) {
1126
1114
  if (/\.css$/.test(source)) return;
1127
1115
  var loadSharePath = getLoadShareModulePath(source);
@@ -1135,7 +1123,7 @@ function proxySharedModule(options) {
1135
1123
  }));
1136
1124
  var savePrebuild = new PromiseStore();
1137
1125
  (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
1138
- return command === "build" ? {
1126
+ return command === 'build' ? {
1139
1127
  find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1140
1128
  replacement: function replacement($1) {
1141
1129
  var pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
@@ -1143,7 +1131,7 @@ function proxySharedModule(options) {
1143
1131
  }
1144
1132
  } : {
1145
1133
  find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1146
- replacement: "$1",
1134
+ replacement: '$1',
1147
1135
  customResolver: function customResolver(source, importer) {
1148
1136
  try {
1149
1137
  var _this = this;
@@ -1169,8 +1157,8 @@ function proxySharedModule(options) {
1169
1157
  }));
1170
1158
  }
1171
1159
  }, {
1172
- name: "watchLocalSharedImportMap",
1173
- apply: "serve",
1160
+ name: 'watchLocalSharedImportMap',
1161
+ apply: 'serve',
1174
1162
  config: function config(_config3) {
1175
1163
  _config3.optimizeDeps = defu(_config3.optimizeDeps, {
1176
1164
  exclude: [getLocalSharedImportMapPath()]
@@ -1227,7 +1215,7 @@ function federation(mfUserOptions) {
1227
1215
  var name = options.name,
1228
1216
  shared = options.shared,
1229
1217
  filename = options.filename;
1230
- if (!name) throw new Error("name is required");
1218
+ if (!name) throw new Error('name is required');
1231
1219
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
1232
1220
  entryName: 'remoteEntry',
1233
1221
  entryPath: REMOTE_ENTRY_ID,
@@ -1235,6 +1223,9 @@ function federation(mfUserOptions) {
1235
1223
  }), addEntry({
1236
1224
  entryName: 'hostInit',
1237
1225
  entryPath: getHostAutoInitPath()
1226
+ }), addEntry({
1227
+ entryName: 'virtualExposes',
1228
+ entryPath: VIRTUAL_EXPOSES
1238
1229
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
1239
1230
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
1240
1231
  }), proxySharedModule({
@@ -1243,12 +1234,15 @@ function federation(mfUserOptions) {
1243
1234
  name: 'module-federation-vite',
1244
1235
  enforce: 'post',
1245
1236
  config: function config(_config, _ref) {
1246
- var _config$optimizeDeps;
1237
+ var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3;
1238
+ // TODO: singleton
1247
1239
  _config.resolve.alias.push({
1248
1240
  find: '@module-federation/runtime',
1249
1241
  replacement: require.resolve('@module-federation/runtime')
1250
1242
  });
1251
1243
  (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
1244
+ (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push('__mf__virtual');
1245
+ (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push('__mf__virtual');
1252
1246
  }
1253
1247
  }], Manifest());
1254
1248
  }