@module-federation/vite 1.0.0-alpha-1aa30c0 → 1.0.0-alpha-c13dc95

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/README.md CHANGED
@@ -9,11 +9,11 @@ This plugin makes Module Federation work together with [Vite](https://vitejs.dev
9
9
 
10
10
  ## Working implementations
11
11
 
12
- ### [React](https://github.com/module-federation/module-federation-examples/tree/master/vite-react-microfrontends)<br>
12
+ ### [Vue](https://github.com/gioboa/vue-microfrontend-demo)
13
13
 
14
- ### [Svelte](https://github.com/module-federation/module-federation-examples/tree/master/vite-svelte-microfrontends)<br>
14
+ ### [React](https://github.com/gioboa/react-microfrontend-demo)<br>
15
15
 
16
- ### [Vue](https://github.com/module-federation/module-federation-examples/tree/master/vite-vue-microfrontends)
16
+ ### [More examples here](https://github.com/module-federation/vite/tree/main/examples)<br>
17
17
 
18
18
  ## Getting started 🚀
19
19
 
package/lib/index.cjs CHANGED
@@ -34,6 +34,7 @@ var addEntry = function addEntry(_ref) {
34
34
  var entryName = _ref.entryName,
35
35
  entryPath = _ref.entryPath,
36
36
  fileName = _ref.fileName;
37
+ var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
37
38
  var entryFiles = [];
38
39
  var htmlFilePath;
39
40
  return [{
@@ -43,7 +44,7 @@ var addEntry = function addEntry(_ref) {
43
44
  var _server$httpServer;
44
45
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
45
46
  var port = server.config.server.port;
46
- fetch(path__namespace.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
47
+ fetch(path__namespace.join("http://localhost:" + port, "" + devEntryPath))["catch"](function (e) {});
47
48
  });
48
49
  server.middlewares.use(function (req, res, next) {
49
50
  if (!fileName) {
@@ -51,13 +52,13 @@ var addEntry = function addEntry(_ref) {
51
52
  return;
52
53
  }
53
54
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
54
- req.url = entryPath;
55
+ req.url = devEntryPath;
55
56
  }
56
57
  next();
57
58
  });
58
59
  },
59
60
  transformIndexHtml: function transformIndexHtml(c) {
60
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
61
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
61
62
  }
62
63
  }, {
63
64
  name: "add-entry",
@@ -309,6 +310,13 @@ function removePathFromNpmPackage(packageString) {
309
310
  // Return the matched package name or the original string if no match is found
310
311
  return match ? match[0] : packageString;
311
312
  }
313
+ function getExtFromNpmPackage(packageString) {
314
+ var pkgName = removePathFromNpmPackage(packageString);
315
+ var subpath = packageString.replace(pkgName, "");
316
+ var parts = subpath.split('.');
317
+ var ext = parts.length > 1 ? "." + parts.pop() : undefined;
318
+ return ext;
319
+ }
312
320
 
313
321
  var nodeModulesDir = function findNodeModulesDir(startDir) {
314
322
  if (startDir === void 0) {
@@ -337,27 +345,34 @@ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "package.json"
337
345
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
338
346
  */
339
347
  var VirtualModule = /*#__PURE__*/function () {
340
- function VirtualModule(name) {
348
+ function VirtualModule(name, ext) {
349
+ if (ext === void 0) {
350
+ ext = ".js";
351
+ }
341
352
  this.originName = void 0;
342
353
  this.inited = false;
354
+ this.ext = void 0;
343
355
  this.originName = name;
356
+ this.ext = ext;
344
357
  }
345
358
  var _proto = VirtualModule.prototype;
346
359
  _proto.getPath = function getPath() {
347
360
  return path.resolve(nodeModulesDir, this.getImportId());
348
361
  };
349
362
  _proto.getImportId = function getImportId() {
350
- return virtualPackageName + "/" + packageNameEncode(this.originName);
363
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
364
+ name = _getNormalizeModuleFe.name;
365
+ return virtualPackageName + "/" + packageNameEncode(name) + "-" + packageNameEncode(this.originName) + this.ext;
351
366
  };
352
367
  _proto.writeSync = function writeSync(code, force) {
353
368
  if (!force && this.inited) return;
354
369
  if (!this.inited) {
355
370
  this.inited = true;
356
371
  }
357
- fs.writeFileSync(this.getPath() + ".js", code);
372
+ fs.writeFileSync(this.getPath(), code);
358
373
  };
359
374
  _proto.write = function write(code) {
360
- fs.writeFile(this.getPath() + ".js", code, function () {});
375
+ fs.writeFile(this.getPath(), code, function () {});
361
376
  };
362
377
  return VirtualModule;
363
378
  }();
@@ -434,11 +449,11 @@ var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
434
449
  var preBuildCacheMap = {};
435
450
  var PREBUILD_TAG = "__prebuild__";
436
451
  function writePreBuildLibPath(pkg) {
437
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
452
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
438
453
  preBuildCacheMap[pkg].writeSync("");
439
454
  }
440
455
  function getPreBuildLibImportId(pkg) {
441
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
456
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
442
457
  var importId = preBuildCacheMap[pkg].getImportId();
443
458
  return importId;
444
459
  }
@@ -448,7 +463,6 @@ function addShare(pkg) {
448
463
  }
449
464
  // *** Expose locally provided shared modules here
450
465
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
451
- localSharedImportMapModule.writeSync("");
452
466
  function getLocalSharedImportMapPath() {
453
467
  if (process.platform === "win32") {
454
468
  return getLocalSharedImportMapPath_windows();
@@ -467,7 +481,7 @@ function writeLoadShareModule(pkg, shareItem, command) {
467
481
  loadShareCacheMap[pkg].writeSync("\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 res = 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 ");
468
482
  }
469
483
 
470
- var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
484
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
471
485
  function generateRemoteEntry(options) {
472
486
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
473
487
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -483,18 +497,39 @@ function generateRemoteEntry(options) {
483
497
  return item[0] + "()";
484
498
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
485
499
  }
486
- var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
487
- wrapRemoteEntryModule.writeSync("\nimport {init, get} from \"" + REMOTE_ENTRY_ID + "\"\nexport {init, get}\n");
488
- var WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
489
- var WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
490
500
  /**
491
501
  * Inject entry file, automatically init when used as host,
492
502
  * and will not inject remoteEntry
493
503
  */
494
504
  var hostAutoInitModule = new VirtualModule("hostAutoInit");
495
- hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
496
- var HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
497
- var HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
505
+ function writeHostAutoInit() {
506
+ hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
507
+ }
508
+ function getHostAutoInitImportId() {
509
+ return hostAutoInitModule.getImportId();
510
+ }
511
+ function getHostAutoInitPath() {
512
+ return hostAutoInitModule.getPath();
513
+ }
514
+
515
+ var remoteVirtualModule = new VirtualModule("remoteModule");
516
+ function writeRemote() {
517
+ remoteVirtualModule.writeSync("");
518
+ }
519
+ function generateRemotes(id, command) {
520
+ return {
521
+ code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
522
+ map: null,
523
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
524
+ syntheticNamedExports: '__mf__dynamicExports'
525
+ };
526
+ }
527
+
528
+ function initVirtualModules() {
529
+ writeLocalSharedImportMap();
530
+ writeHostAutoInit();
531
+ writeRemote();
532
+ }
498
533
 
499
534
  var filter$1 = pluginutils.createFilter();
500
535
  function pluginProxyRemoteEntry () {
@@ -525,17 +560,6 @@ function pluginProxyRemoteEntry () {
525
560
  };
526
561
  }
527
562
 
528
- var remoteVirtualModule = new VirtualModule("remoteModule");
529
- remoteVirtualModule.writeSync("");
530
- function generateRemotes(id, command) {
531
- return {
532
- code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
533
- map: null,
534
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
535
- syntheticNamedExports: '__mf__dynamicExports'
536
- };
537
- }
538
-
539
563
  var filter = pluginutils.createFilter();
540
564
  function pluginProxyRemotes (options) {
541
565
  var command;
@@ -701,25 +725,29 @@ function proxySharedModule(options) {
701
725
  var savePrebuild = new PromiseStore();
702
726
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
703
727
  return command === "build" ? {
704
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
705
- replacement: function replacement(_, $1) {
706
- return packageNameDecode($1);
728
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
729
+ replacement: function replacement($1) {
730
+ $1 = $1.replace(/\.[^.]+$/, "");
731
+ var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
732
+ return packageNameDecode(pkgName);
707
733
  }
708
734
  } : {
709
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
735
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
710
736
  replacement: "$1",
711
737
  customResolver: function customResolver(source, importer) {
712
738
  try {
713
739
  var _this = this;
740
+ source = source.replace(/\.[^.]+$/, "");
741
+ var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
714
742
  if (importer.includes(LOAD_SHARE_TAG)) {
715
743
  // save pre-bunding module id
716
- savePrebuild.set(source, _this.resolve(packageNameDecode(source)).then(function (item) {
744
+ savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
717
745
  return item.id;
718
746
  }));
719
747
  }
720
748
  // Fix localSharedImportMap import id
721
749
  var _resolve = _this.resolve;
722
- return Promise.resolve(savePrebuild.get(source)).then(function (_savePrebuild$get) {
750
+ return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
723
751
  return Promise.resolve(_resolve.call(_this, _savePrebuild$get));
724
752
  });
725
753
  } catch (e) {
@@ -838,6 +866,8 @@ var normalizeOptimizeDepsPlugin = {
838
866
  _config.optimizeDeps = {};
839
867
  optimizeDeps = _config.optimizeDeps;
840
868
  }
869
+ // todo: fix this workaround
870
+ optimizeDeps.force = true;
841
871
  if (!optimizeDeps.include) optimizeDeps.include = [];
842
872
  if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
843
873
  }
@@ -845,19 +875,20 @@ var normalizeOptimizeDepsPlugin = {
845
875
 
846
876
  function federation(mfUserOptions) {
847
877
  var options = normalizeModuleFederationOptions(mfUserOptions);
878
+ initVirtualModules();
848
879
  var name = options.name,
849
880
  shared = options.shared,
850
881
  filename = options.filename;
851
882
  if (!name) throw new Error("name is required");
852
883
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
853
884
  entryName: 'remoteEntry',
854
- entryPath: WRAP_REMOTE_ENTRY_PATH,
885
+ entryPath: REMOTE_ENTRY_ID,
855
886
  fileName: filename
856
887
  }), addEntry({
857
888
  entryName: 'hostInit',
858
- entryPath: HOST_AUTO_INIT_PATH
889
+ entryPath: getHostAutoInitPath()
859
890
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
860
- return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
891
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
861
892
  }), proxySharedModule({
862
893
  shared: shared
863
894
  }), [{
package/lib/index.esm.js CHANGED
@@ -11,6 +11,7 @@ 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
15
  var entryFiles = [];
15
16
  var htmlFilePath;
16
17
  return [{
@@ -20,7 +21,7 @@ var addEntry = function addEntry(_ref) {
20
21
  var _server$httpServer;
21
22
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
22
23
  var port = server.config.server.port;
23
- fetch(path.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
24
+ fetch(path.join("http://localhost:" + port, "" + devEntryPath))["catch"](function (e) {});
24
25
  });
25
26
  server.middlewares.use(function (req, res, next) {
26
27
  if (!fileName) {
@@ -28,13 +29,13 @@ var addEntry = function addEntry(_ref) {
28
29
  return;
29
30
  }
30
31
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
31
- req.url = entryPath;
32
+ req.url = devEntryPath;
32
33
  }
33
34
  next();
34
35
  });
35
36
  },
36
37
  transformIndexHtml: function transformIndexHtml(c) {
37
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
38
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
38
39
  }
39
40
  }, {
40
41
  name: "add-entry",
@@ -286,6 +287,13 @@ function removePathFromNpmPackage(packageString) {
286
287
  // Return the matched package name or the original string if no match is found
287
288
  return match ? match[0] : packageString;
288
289
  }
290
+ function getExtFromNpmPackage(packageString) {
291
+ var pkgName = removePathFromNpmPackage(packageString);
292
+ var subpath = packageString.replace(pkgName, "");
293
+ var parts = subpath.split('.');
294
+ var ext = parts.length > 1 ? "." + parts.pop() : undefined;
295
+ return ext;
296
+ }
289
297
 
290
298
  var nodeModulesDir = function findNodeModulesDir(startDir) {
291
299
  if (startDir === void 0) {
@@ -314,27 +322,34 @@ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.
314
322
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
315
323
  */
316
324
  var VirtualModule = /*#__PURE__*/function () {
317
- function VirtualModule(name) {
325
+ function VirtualModule(name, ext) {
326
+ if (ext === void 0) {
327
+ ext = ".js";
328
+ }
318
329
  this.originName = void 0;
319
330
  this.inited = false;
331
+ this.ext = void 0;
320
332
  this.originName = name;
333
+ this.ext = ext;
321
334
  }
322
335
  var _proto = VirtualModule.prototype;
323
336
  _proto.getPath = function getPath() {
324
337
  return resolve(nodeModulesDir, this.getImportId());
325
338
  };
326
339
  _proto.getImportId = function getImportId() {
327
- return virtualPackageName + "/" + packageNameEncode(this.originName);
340
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
341
+ name = _getNormalizeModuleFe.name;
342
+ return virtualPackageName + "/" + packageNameEncode(name) + "-" + packageNameEncode(this.originName) + this.ext;
328
343
  };
329
344
  _proto.writeSync = function writeSync(code, force) {
330
345
  if (!force && this.inited) return;
331
346
  if (!this.inited) {
332
347
  this.inited = true;
333
348
  }
334
- writeFileSync(this.getPath() + ".js", code);
349
+ writeFileSync(this.getPath(), code);
335
350
  };
336
351
  _proto.write = function write(code) {
337
- writeFile(this.getPath() + ".js", code, function () {});
352
+ writeFile(this.getPath(), code, function () {});
338
353
  };
339
354
  return VirtualModule;
340
355
  }();
@@ -411,11 +426,11 @@ var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
411
426
  var preBuildCacheMap = {};
412
427
  var PREBUILD_TAG = "__prebuild__";
413
428
  function writePreBuildLibPath(pkg) {
414
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
429
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
415
430
  preBuildCacheMap[pkg].writeSync("");
416
431
  }
417
432
  function getPreBuildLibImportId(pkg) {
418
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
433
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
419
434
  var importId = preBuildCacheMap[pkg].getImportId();
420
435
  return importId;
421
436
  }
@@ -425,7 +440,6 @@ function addShare(pkg) {
425
440
  }
426
441
  // *** Expose locally provided shared modules here
427
442
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
428
- localSharedImportMapModule.writeSync("");
429
443
  function getLocalSharedImportMapPath() {
430
444
  if (process.platform === "win32") {
431
445
  return getLocalSharedImportMapPath_windows();
@@ -444,7 +458,7 @@ function writeLoadShareModule(pkg, shareItem, command) {
444
458
  loadShareCacheMap[pkg].writeSync("\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 res = 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 ");
445
459
  }
446
460
 
447
- var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
461
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
448
462
  function generateRemoteEntry(options) {
449
463
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
450
464
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -460,18 +474,39 @@ function generateRemoteEntry(options) {
460
474
  return item[0] + "()";
461
475
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
462
476
  }
463
- var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
464
- wrapRemoteEntryModule.writeSync("\nimport {init, get} from \"" + REMOTE_ENTRY_ID + "\"\nexport {init, get}\n");
465
- var WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
466
- var WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
467
477
  /**
468
478
  * Inject entry file, automatically init when used as host,
469
479
  * and will not inject remoteEntry
470
480
  */
471
481
  var hostAutoInitModule = new VirtualModule("hostAutoInit");
472
- hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
473
- var HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
474
- var HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
482
+ function writeHostAutoInit() {
483
+ hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
484
+ }
485
+ function getHostAutoInitImportId() {
486
+ return hostAutoInitModule.getImportId();
487
+ }
488
+ function getHostAutoInitPath() {
489
+ return hostAutoInitModule.getPath();
490
+ }
491
+
492
+ var remoteVirtualModule = new VirtualModule("remoteModule");
493
+ function writeRemote() {
494
+ remoteVirtualModule.writeSync("");
495
+ }
496
+ function generateRemotes(id, command) {
497
+ return {
498
+ code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
499
+ map: null,
500
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
501
+ syntheticNamedExports: '__mf__dynamicExports'
502
+ };
503
+ }
504
+
505
+ function initVirtualModules() {
506
+ writeLocalSharedImportMap();
507
+ writeHostAutoInit();
508
+ writeRemote();
509
+ }
475
510
 
476
511
  var filter$1 = createFilter();
477
512
  function pluginProxyRemoteEntry () {
@@ -502,17 +537,6 @@ function pluginProxyRemoteEntry () {
502
537
  };
503
538
  }
504
539
 
505
- var remoteVirtualModule = new VirtualModule("remoteModule");
506
- remoteVirtualModule.writeSync("");
507
- function generateRemotes(id, command) {
508
- return {
509
- code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
510
- map: null,
511
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
512
- syntheticNamedExports: '__mf__dynamicExports'
513
- };
514
- }
515
-
516
540
  var filter = createFilter();
517
541
  function pluginProxyRemotes (options) {
518
542
  var command;
@@ -678,25 +702,29 @@ function proxySharedModule(options) {
678
702
  var savePrebuild = new PromiseStore();
679
703
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
680
704
  return command === "build" ? {
681
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
682
- replacement: function replacement(_, $1) {
683
- return packageNameDecode($1);
705
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
706
+ replacement: function replacement($1) {
707
+ $1 = $1.replace(/\.[^.]+$/, "");
708
+ var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
709
+ return packageNameDecode(pkgName);
684
710
  }
685
711
  } : {
686
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
712
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
687
713
  replacement: "$1",
688
714
  customResolver: function customResolver(source, importer) {
689
715
  try {
690
716
  var _this = this;
717
+ source = source.replace(/\.[^.]+$/, "");
718
+ var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
691
719
  if (importer.includes(LOAD_SHARE_TAG)) {
692
720
  // save pre-bunding module id
693
- savePrebuild.set(source, _this.resolve(packageNameDecode(source)).then(function (item) {
721
+ savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
694
722
  return item.id;
695
723
  }));
696
724
  }
697
725
  // Fix localSharedImportMap import id
698
726
  var _resolve = _this.resolve;
699
- return Promise.resolve(savePrebuild.get(source)).then(function (_savePrebuild$get) {
727
+ return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
700
728
  return Promise.resolve(_resolve.call(_this, _savePrebuild$get));
701
729
  });
702
730
  } catch (e) {
@@ -815,6 +843,8 @@ var normalizeOptimizeDepsPlugin = {
815
843
  _config.optimizeDeps = {};
816
844
  optimizeDeps = _config.optimizeDeps;
817
845
  }
846
+ // todo: fix this workaround
847
+ optimizeDeps.force = true;
818
848
  if (!optimizeDeps.include) optimizeDeps.include = [];
819
849
  if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
820
850
  }
@@ -822,19 +852,20 @@ var normalizeOptimizeDepsPlugin = {
822
852
 
823
853
  function federation(mfUserOptions) {
824
854
  var options = normalizeModuleFederationOptions(mfUserOptions);
855
+ initVirtualModules();
825
856
  var name = options.name,
826
857
  shared = options.shared,
827
858
  filename = options.filename;
828
859
  if (!name) throw new Error("name is required");
829
860
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
830
861
  entryName: 'remoteEntry',
831
- entryPath: WRAP_REMOTE_ENTRY_PATH,
862
+ entryPath: REMOTE_ENTRY_ID,
832
863
  fileName: filename
833
864
  }), addEntry({
834
865
  entryName: 'hostInit',
835
- entryPath: HOST_AUTO_INIT_PATH
866
+ entryPath: getHostAutoInitPath()
836
867
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
837
- return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
868
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
838
869
  }), proxySharedModule({
839
870
  shared: shared
840
871
  }), [{
@@ -12,6 +12,7 @@ const addEntry = ({
12
12
  entryPath,
13
13
  fileName
14
14
  }) => {
15
+ const devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
15
16
  let entryFiles = [];
16
17
  let htmlFilePath;
17
18
  return [{
@@ -23,7 +24,7 @@ const addEntry = ({
23
24
  const {
24
25
  port
25
26
  } = server.config.server;
26
- fetch(path.join(`http://localhost:${port}`, `${entryPath}`)).catch(e => {});
27
+ fetch(path.join(`http://localhost:${port}`, `${devEntryPath}`)).catch(e => {});
27
28
  });
28
29
  server.middlewares.use((req, res, next) => {
29
30
  if (!fileName) {
@@ -31,13 +32,13 @@ const addEntry = ({
31
32
  return;
32
33
  }
33
34
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
34
- req.url = entryPath;
35
+ req.url = devEntryPath;
35
36
  }
36
37
  next();
37
38
  });
38
39
  },
39
40
  transformIndexHtml(c) {
40
- return c.replace('<head>', `<head><script type="module" src=${JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/'))}></script>`);
41
+ return c.replace('<head>', `<head><script type="module" src=${JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/'))}></script>`);
41
42
  }
42
43
  }, {
43
44
  name: "add-entry",
@@ -291,6 +292,13 @@ function removePathFromNpmPackage(packageString) {
291
292
  // Return the matched package name or the original string if no match is found
292
293
  return match ? match[0] : packageString;
293
294
  }
295
+ function getExtFromNpmPackage(packageString) {
296
+ const pkgName = removePathFromNpmPackage(packageString);
297
+ const subpath = packageString.replace(pkgName, "");
298
+ const parts = subpath.split('.');
299
+ const ext = parts.length > 1 ? "." + parts.pop() : undefined;
300
+ return ext;
301
+ }
294
302
 
295
303
  const nodeModulesDir = function findNodeModulesDir(startDir = process.cwd()) {
296
304
  let currentDir = startDir;
@@ -316,26 +324,31 @@ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.
316
324
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
317
325
  */
318
326
  class VirtualModule {
319
- constructor(name) {
327
+ constructor(name, ext = ".js") {
320
328
  this.originName = void 0;
321
329
  this.inited = false;
330
+ this.ext = void 0;
322
331
  this.originName = name;
332
+ this.ext = ext;
323
333
  }
324
334
  getPath() {
325
335
  return resolve(nodeModulesDir, this.getImportId());
326
336
  }
327
337
  getImportId() {
328
- return `${virtualPackageName}/${packageNameEncode(this.originName)}`;
338
+ const {
339
+ name
340
+ } = getNormalizeModuleFederationOptions();
341
+ return `${virtualPackageName}/${packageNameEncode(name)}-${packageNameEncode(this.originName)}${this.ext}`;
329
342
  }
330
343
  writeSync(code, force) {
331
344
  if (!force && this.inited) return;
332
345
  if (!this.inited) {
333
346
  this.inited = true;
334
347
  }
335
- writeFileSync(this.getPath() + ".js", code);
348
+ writeFileSync(this.getPath(), code);
336
349
  }
337
350
  write(code) {
338
- writeFile(this.getPath() + ".js", code, function () {});
351
+ writeFile(this.getPath(), code, function () {});
339
352
  }
340
353
  }
341
354
 
@@ -369,11 +382,11 @@ function createFile(filePath, content) {
369
382
  const preBuildCacheMap = {};
370
383
  const PREBUILD_TAG = "__prebuild__";
371
384
  function writePreBuildLibPath(pkg) {
372
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
385
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
373
386
  preBuildCacheMap[pkg].writeSync("");
374
387
  }
375
388
  function getPreBuildLibImportId(pkg) {
376
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
389
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
377
390
  const importId = preBuildCacheMap[pkg].getImportId();
378
391
  return importId;
379
392
  }
@@ -383,7 +396,6 @@ function addShare(pkg) {
383
396
  }
384
397
  // *** Expose locally provided shared modules here
385
398
  const localSharedImportMapModule = new VirtualModule("localSharedImportMap");
386
- localSharedImportMapModule.writeSync("");
387
399
  function getLocalSharedImportMapPath() {
388
400
  if (process.platform === "win32") {
389
401
  return getLocalSharedImportMapPath_windows();
@@ -473,7 +485,7 @@ function writeLoadShareModule(pkg, shareItem, command) {
473
485
  `);
474
486
  }
475
487
 
476
- const REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
488
+ const REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
477
489
  function generateRemoteEntry(options) {
478
490
  const pluginImportNames = options.runtimePlugins.map((p, i) => [`$runtimePlugin_${i}`, `import $runtimePlugin_${i} from "${p}";`]);
479
491
  return `
@@ -530,24 +542,52 @@ function generateRemoteEntry(options) {
530
542
  }
531
543
  `;
532
544
  }
533
- const wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
534
- wrapRemoteEntryModule.writeSync(`
535
- import {init, get} from "${REMOTE_ENTRY_ID}"
536
- export {init, get}
537
- `);
538
- const WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
539
- const WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
540
545
  /**
541
546
  * Inject entry file, automatically init when used as host,
542
547
  * and will not inject remoteEntry
543
548
  */
544
549
  const hostAutoInitModule = new VirtualModule("hostAutoInit");
545
- hostAutoInitModule.writeSync(`
550
+ function writeHostAutoInit() {
551
+ hostAutoInitModule.writeSync(`
546
552
  import {init} from "${REMOTE_ENTRY_ID}"
547
553
  init()
548
554
  `);
549
- const HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
550
- const HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
555
+ }
556
+ function getHostAutoInitImportId() {
557
+ return hostAutoInitModule.getImportId();
558
+ }
559
+ function getHostAutoInitPath() {
560
+ return hostAutoInitModule.getPath();
561
+ }
562
+
563
+ const remoteVirtualModule = new VirtualModule("remoteModule");
564
+ function writeRemote() {
565
+ remoteVirtualModule.writeSync("");
566
+ }
567
+ function generateRemotes(id, command) {
568
+ return {
569
+ code: `
570
+ import {loadRemote} from "@module-federation/runtime"
571
+ const exportModule = await loadRemote(${JSON.stringify(id)})
572
+ ${command === "build" && `
573
+ export default 'default' in (exportModule || {}) ? exportModule.default : undefined
574
+ export const __mf__dynamicExports = exportModule
575
+ ` || ""}
576
+ ${command !== "build" && `
577
+ export default exportModule
578
+ ` || ""}
579
+ `,
580
+ map: null,
581
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
582
+ syntheticNamedExports: '__mf__dynamicExports'
583
+ };
584
+ }
585
+
586
+ function initVirtualModules() {
587
+ writeLocalSharedImportMap();
588
+ writeHostAutoInit();
589
+ writeRemote();
590
+ }
551
591
 
552
592
  const filter$1 = createFilter();
553
593
  function pluginProxyRemoteEntry () {
@@ -573,27 +613,6 @@ function pluginProxyRemoteEntry () {
573
613
  };
574
614
  }
575
615
 
576
- const remoteVirtualModule = new VirtualModule("remoteModule");
577
- remoteVirtualModule.writeSync("");
578
- function generateRemotes(id, command) {
579
- return {
580
- code: `
581
- import {loadRemote} from "@module-federation/runtime"
582
- const exportModule = await loadRemote(${JSON.stringify(id)})
583
- ${command === "build" && `
584
- export default 'default' in (exportModule || {}) ? exportModule.default : undefined
585
- export const __mf__dynamicExports = exportModule
586
- ` || ""}
587
- ${command !== "build" && `
588
- export default exportModule
589
- ` || ""}
590
- `,
591
- map: null,
592
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
593
- syntheticNamedExports: '__mf__dynamicExports'
594
- };
595
- }
596
-
597
616
  const filter = createFilter();
598
617
  function pluginProxyRemotes (options) {
599
618
  let command;
@@ -750,20 +769,24 @@ function proxySharedModule(options) {
750
769
  const savePrebuild = new PromiseStore();
751
770
  config.resolve.alias.push(...Object.keys(shared).map(key => {
752
771
  return command === "build" ? {
753
- find: new RegExp(`${virtualPackageName}/${PREBUILD_TAG}(.+)`),
754
- replacement: function (_, $1) {
755
- return packageNameDecode($1);
772
+ find: new RegExp(`(.*${PREBUILD_TAG}(.+))`),
773
+ replacement: function ($1) {
774
+ $1 = $1.replace(/\.[^.]+$/, "");
775
+ const pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
776
+ return packageNameDecode(pkgName);
756
777
  }
757
778
  } : {
758
- find: new RegExp(`${virtualPackageName}/${PREBUILD_TAG}(.+)`),
779
+ find: new RegExp(`(.*${PREBUILD_TAG}(.+))`),
759
780
  replacement: "$1",
760
781
  async customResolver(source, importer) {
782
+ source = source.replace(/\.[^.]+$/, "");
783
+ const pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
761
784
  if (importer.includes(LOAD_SHARE_TAG)) {
762
785
  // save pre-bunding module id
763
- savePrebuild.set(source, this.resolve(packageNameDecode(source)).then(item => item.id));
786
+ savePrebuild.set(pkgName, this.resolve(pkgName).then(item => item.id));
764
787
  }
765
788
  // Fix localSharedImportMap import id
766
- return await this.resolve(await savePrebuild.get(source));
789
+ return await this.resolve(await savePrebuild.get(pkgName));
767
790
  }
768
791
  };
769
792
  }));
@@ -887,6 +910,8 @@ var normalizeOptimizeDepsPlugin = {
887
910
  config.optimizeDeps = {};
888
911
  optimizeDeps = config.optimizeDeps;
889
912
  }
913
+ // todo: fix this workaround
914
+ optimizeDeps.force = true;
890
915
  if (!optimizeDeps.include) optimizeDeps.include = [];
891
916
  if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
892
917
  }
@@ -894,6 +919,7 @@ var normalizeOptimizeDepsPlugin = {
894
919
 
895
920
  function federation(mfUserOptions) {
896
921
  const options = normalizeModuleFederationOptions(mfUserOptions);
922
+ initVirtualModules();
897
923
  const {
898
924
  name,
899
925
  remotes,
@@ -903,13 +929,13 @@ function federation(mfUserOptions) {
903
929
  if (!name) throw new Error("name is required");
904
930
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, ...addEntry({
905
931
  entryName: 'remoteEntry',
906
- entryPath: WRAP_REMOTE_ENTRY_PATH,
932
+ entryPath: REMOTE_ENTRY_ID,
907
933
  fileName: filename
908
934
  }), ...addEntry({
909
935
  entryName: 'hostInit',
910
- entryPath: HOST_AUTO_INIT_PATH
936
+ entryPath: getHostAutoInitPath()
911
937
  }), pluginProxyRemoteEntry(), pluginProxyRemotes(options), ...pluginModuleParseEnd(id => {
912
- return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
938
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
913
939
  }), ...proxySharedModule({
914
940
  shared
915
941
  }), {
package/lib/index.umd.js CHANGED
@@ -32,6 +32,7 @@
32
32
  var entryName = _ref.entryName,
33
33
  entryPath = _ref.entryPath,
34
34
  fileName = _ref.fileName;
35
+ var devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
35
36
  var entryFiles = [];
36
37
  var htmlFilePath;
37
38
  return [{
@@ -41,7 +42,7 @@
41
42
  var _server$httpServer;
42
43
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
43
44
  var port = server.config.server.port;
44
- fetch(path__namespace.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
45
+ fetch(path__namespace.join("http://localhost:" + port, "" + devEntryPath))["catch"](function (e) {});
45
46
  });
46
47
  server.middlewares.use(function (req, res, next) {
47
48
  if (!fileName) {
@@ -49,13 +50,13 @@
49
50
  return;
50
51
  }
51
52
  if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
52
- req.url = entryPath;
53
+ req.url = devEntryPath;
53
54
  }
54
55
  next();
55
56
  });
56
57
  },
57
58
  transformIndexHtml: function transformIndexHtml(c) {
58
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
59
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
59
60
  }
60
61
  }, {
61
62
  name: "add-entry",
@@ -307,6 +308,13 @@
307
308
  // Return the matched package name or the original string if no match is found
308
309
  return match ? match[0] : packageString;
309
310
  }
311
+ function getExtFromNpmPackage(packageString) {
312
+ var pkgName = removePathFromNpmPackage(packageString);
313
+ var subpath = packageString.replace(pkgName, "");
314
+ var parts = subpath.split('.');
315
+ var ext = parts.length > 1 ? "." + parts.pop() : undefined;
316
+ return ext;
317
+ }
310
318
 
311
319
  var nodeModulesDir = function findNodeModulesDir(startDir) {
312
320
  if (startDir === void 0) {
@@ -335,27 +343,34 @@
335
343
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
336
344
  */
337
345
  var VirtualModule = /*#__PURE__*/function () {
338
- function VirtualModule(name) {
346
+ function VirtualModule(name, ext) {
347
+ if (ext === void 0) {
348
+ ext = ".js";
349
+ }
339
350
  this.originName = void 0;
340
351
  this.inited = false;
352
+ this.ext = void 0;
341
353
  this.originName = name;
354
+ this.ext = ext;
342
355
  }
343
356
  var _proto = VirtualModule.prototype;
344
357
  _proto.getPath = function getPath() {
345
358
  return path.resolve(nodeModulesDir, this.getImportId());
346
359
  };
347
360
  _proto.getImportId = function getImportId() {
348
- return virtualPackageName + "/" + packageNameEncode(this.originName);
361
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
362
+ name = _getNormalizeModuleFe.name;
363
+ return virtualPackageName + "/" + packageNameEncode(name) + "-" + packageNameEncode(this.originName) + this.ext;
349
364
  };
350
365
  _proto.writeSync = function writeSync(code, force) {
351
366
  if (!force && this.inited) return;
352
367
  if (!this.inited) {
353
368
  this.inited = true;
354
369
  }
355
- fs.writeFileSync(this.getPath() + ".js", code);
370
+ fs.writeFileSync(this.getPath(), code);
356
371
  };
357
372
  _proto.write = function write(code) {
358
- fs.writeFile(this.getPath() + ".js", code, function () {});
373
+ fs.writeFile(this.getPath(), code, function () {});
359
374
  };
360
375
  return VirtualModule;
361
376
  }();
@@ -432,11 +447,11 @@
432
447
  var preBuildCacheMap = {};
433
448
  var PREBUILD_TAG = "__prebuild__";
434
449
  function writePreBuildLibPath(pkg) {
435
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
450
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
436
451
  preBuildCacheMap[pkg].writeSync("");
437
452
  }
438
453
  function getPreBuildLibImportId(pkg) {
439
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
454
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
440
455
  var importId = preBuildCacheMap[pkg].getImportId();
441
456
  return importId;
442
457
  }
@@ -446,7 +461,6 @@
446
461
  }
447
462
  // *** Expose locally provided shared modules here
448
463
  var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
449
- localSharedImportMapModule.writeSync("");
450
464
  function getLocalSharedImportMapPath() {
451
465
  if (process.platform === "win32") {
452
466
  return getLocalSharedImportMapPath_windows();
@@ -465,7 +479,7 @@
465
479
  loadShareCacheMap[pkg].writeSync("\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 res = 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 ");
466
480
  }
467
481
 
468
- var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
482
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
469
483
  function generateRemoteEntry(options) {
470
484
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
471
485
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -481,18 +495,39 @@
481
495
  return item[0] + "()";
482
496
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
483
497
  }
484
- var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
485
- wrapRemoteEntryModule.writeSync("\nimport {init, get} from \"" + REMOTE_ENTRY_ID + "\"\nexport {init, get}\n");
486
- var WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
487
- var WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
488
498
  /**
489
499
  * Inject entry file, automatically init when used as host,
490
500
  * and will not inject remoteEntry
491
501
  */
492
502
  var hostAutoInitModule = new VirtualModule("hostAutoInit");
493
- hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
494
- var HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
495
- var HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
503
+ function writeHostAutoInit() {
504
+ hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
505
+ }
506
+ function getHostAutoInitImportId() {
507
+ return hostAutoInitModule.getImportId();
508
+ }
509
+ function getHostAutoInitPath() {
510
+ return hostAutoInitModule.getPath();
511
+ }
512
+
513
+ var remoteVirtualModule = new VirtualModule("remoteModule");
514
+ function writeRemote() {
515
+ remoteVirtualModule.writeSync("");
516
+ }
517
+ function generateRemotes(id, command) {
518
+ return {
519
+ code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
520
+ map: null,
521
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
522
+ syntheticNamedExports: '__mf__dynamicExports'
523
+ };
524
+ }
525
+
526
+ function initVirtualModules() {
527
+ writeLocalSharedImportMap();
528
+ writeHostAutoInit();
529
+ writeRemote();
530
+ }
496
531
 
497
532
  var filter$1 = pluginutils.createFilter();
498
533
  function pluginProxyRemoteEntry () {
@@ -523,17 +558,6 @@
523
558
  };
524
559
  }
525
560
 
526
- var remoteVirtualModule = new VirtualModule("remoteModule");
527
- remoteVirtualModule.writeSync("");
528
- function generateRemotes(id, command) {
529
- return {
530
- code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
531
- map: null,
532
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
533
- syntheticNamedExports: '__mf__dynamicExports'
534
- };
535
- }
536
-
537
561
  var filter = pluginutils.createFilter();
538
562
  function pluginProxyRemotes (options) {
539
563
  var command;
@@ -699,25 +723,29 @@
699
723
  var savePrebuild = new PromiseStore();
700
724
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
701
725
  return command === "build" ? {
702
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
703
- replacement: function replacement(_, $1) {
704
- return packageNameDecode($1);
726
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
727
+ replacement: function replacement($1) {
728
+ $1 = $1.replace(/\.[^.]+$/, "");
729
+ var pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
730
+ return packageNameDecode(pkgName);
705
731
  }
706
732
  } : {
707
- find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
733
+ find: new RegExp("(.*" + PREBUILD_TAG + "(.+))"),
708
734
  replacement: "$1",
709
735
  customResolver: function customResolver(source, importer) {
710
736
  try {
711
737
  var _this = this;
738
+ source = source.replace(/\.[^.]+$/, "");
739
+ var pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
712
740
  if (importer.includes(LOAD_SHARE_TAG)) {
713
741
  // save pre-bunding module id
714
- savePrebuild.set(source, _this.resolve(packageNameDecode(source)).then(function (item) {
742
+ savePrebuild.set(pkgName, _this.resolve(pkgName).then(function (item) {
715
743
  return item.id;
716
744
  }));
717
745
  }
718
746
  // Fix localSharedImportMap import id
719
747
  var _resolve = _this.resolve;
720
- return Promise.resolve(savePrebuild.get(source)).then(function (_savePrebuild$get) {
748
+ return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
721
749
  return Promise.resolve(_resolve.call(_this, _savePrebuild$get));
722
750
  });
723
751
  } catch (e) {
@@ -836,6 +864,8 @@
836
864
  _config.optimizeDeps = {};
837
865
  optimizeDeps = _config.optimizeDeps;
838
866
  }
867
+ // todo: fix this workaround
868
+ optimizeDeps.force = true;
839
869
  if (!optimizeDeps.include) optimizeDeps.include = [];
840
870
  if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
841
871
  }
@@ -843,19 +873,20 @@
843
873
 
844
874
  function federation(mfUserOptions) {
845
875
  var options = normalizeModuleFederationOptions(mfUserOptions);
876
+ initVirtualModules();
846
877
  var name = options.name,
847
878
  shared = options.shared,
848
879
  filename = options.filename;
849
880
  if (!name) throw new Error("name is required");
850
881
  return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
851
882
  entryName: 'remoteEntry',
852
- entryPath: WRAP_REMOTE_ENTRY_PATH,
883
+ entryPath: REMOTE_ENTRY_ID,
853
884
  fileName: filename
854
885
  }), addEntry({
855
886
  entryName: 'hostInit',
856
- entryPath: HOST_AUTO_INIT_PATH
887
+ entryPath: getHostAutoInitPath()
857
888
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
858
- return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
889
+ return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
859
890
  }), proxySharedModule({
860
891
  shared: shared
861
892
  }), [{
@@ -5,7 +5,8 @@ export declare const virtualPackageName = "__mf__virtual";
5
5
  export default class VirtualModule {
6
6
  originName: string;
7
7
  inited: boolean;
8
- constructor(name: string);
8
+ ext: string;
9
+ constructor(name: string, ext?: string);
9
10
  getPath(): string;
10
11
  getImportId(): string;
11
12
  writeSync(code: string, force?: boolean): void;
@@ -15,3 +15,4 @@ export declare function packageNameEncode(name: string): string;
15
15
  */
16
16
  export declare function packageNameDecode(global: string): string;
17
17
  export declare function removePathFromNpmPackage(packageString: string): string;
18
+ export declare function getExtFromNpmPackage(packageString: string): string | undefined;
@@ -0,0 +1,4 @@
1
+ export { generateRemoteEntry, getHostAutoInitImportId, getHostAutoInitPath, REMOTE_ENTRY_ID } from "./virtualRemoteEntry";
2
+ export { generateRemotes, remoteVirtualModule } from "./virtualRemotes";
3
+ export { addShare, generateLocalSharedImportMap, getLoadShareModulePath, getLocalSharedImportMapPath, getPreBuildLibImportId, LOAD_SHARE_TAG, localSharedImportMapModule, PREBUILD_TAG, writeLoadShareModule, writeLocalSharedImportMap, writePreBuildLibPath } from "./virtualShared_preBuild";
4
+ export declare function initVirtualModules(): void;
@@ -1,7 +1,6 @@
1
1
  import { NormalizedModuleFederationOptions } from '../utils/normalizeModuleFederationOptions';
2
- export declare const REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
2
+ export declare const REMOTE_ENTRY_ID = "virtual:mf-REMOTE_ENTRY_ID";
3
3
  export declare function generateRemoteEntry(options: NormalizedModuleFederationOptions): string;
4
- export declare const WRAP_REMOTE_ENTRY_QUERY_STR: string;
5
- export declare const WRAP_REMOTE_ENTRY_PATH: string;
6
- export declare const HOST_AUTO_INIT_QUERY_STR: string;
7
- export declare const HOST_AUTO_INIT_PATH: string;
4
+ export declare function writeHostAutoInit(): void;
5
+ export declare function getHostAutoInitImportId(): string;
6
+ export declare function getHostAutoInitPath(): string;
@@ -1,5 +1,6 @@
1
1
  import VirtualModule from "../utils/VirtualModule";
2
2
  export declare const remoteVirtualModule: VirtualModule;
3
+ export declare function writeRemote(): void;
3
4
  export declare function generateRemotes(id: string, command: string): {
4
5
  code: string;
5
6
  map: null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.0.0-alpha-1aa30c0",
3
+ "version": "1.0.0-alpha-c13dc95",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "source": "src/index.ts",
@@ -16,7 +16,8 @@
16
16
  "build": "rimraf lib && microbundle --no-sourcemap --compress=false",
17
17
  "dev-rv": "pnpm -filter 'examples-rust-vite*' run dev",
18
18
  "dev-vv": "pnpm -filter 'examples-vite-vite*' run dev",
19
- "preview-vv": "pnpm -filter 'examples-vite-vite*' run preview"
19
+ "dev-nv": "pnpm -filter 'examples-nuxt-vite-host' -filter 'examples-vite-vite-remote' run dev",
20
+ "preview-vv": "pnpm -filter 'examples-vite-vite*' run preview"
20
21
  },
21
22
  "repository": {
22
23
  "type": "git",
@@ -39,7 +40,7 @@
39
40
  "homepage": "https://github.com/module-federation/vite#readme",
40
41
  "packageManager": "pnpm@9.1.3",
41
42
  "dependencies": {
42
- "@module-federation/runtime": "^0.5.0",
43
+ "@module-federation/runtime": "^0.6.0",
43
44
  "@rollup/pluginutils": "^5.1.0",
44
45
  "estree-walker": "^2",
45
46
  "magic-string": "^0.30.11",
@@ -52,6 +53,6 @@
52
53
  "mime-types": "^2.1.35",
53
54
  "pretty-quick": "^4.0.0",
54
55
  "rimraf": "^6.0.1",
55
- "vite": "^5.4.1"
56
+ "vite": "^5.4.3"
56
57
  }
57
58
  }