@module-federation/vite 1.0.0-alpha-10e1f83 → 1.0.0-alpha-51eeeb6

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
@@ -56,6 +56,11 @@ export default defineConfig({
56
56
  // If you set build.target: "chrome89", you can remove this plugin
57
57
  // topLevelAwait(),
58
58
  ],
59
+ server: {
60
+ port: 5173,
61
+ // dev mode please set origin
62
+ origin: "http://localhost:5173"
63
+ },
59
64
  build: {
60
65
  target: 'chrome89',
61
66
  },
@@ -72,6 +77,7 @@ export default defineConfig({
72
77
  - feat: download remote d.ts
73
78
  - feat: generate d.ts
74
79
  - feat: support @vitejs/plugin-legacy
80
+ - feat: Another plugin, when only some remote modules are started, automatically completes HMR[(#54)](https://github.com/module-federation/vite/issues/54)
75
81
 
76
82
  ### So far so good 🎉
77
83
 
package/lib/index.cjs CHANGED
@@ -29,7 +29,8 @@ var path__namespace = /*#__PURE__*/_interopNamespace(path);
29
29
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
30
30
 
31
31
  var addEntry = function addEntry(_ref) {
32
- var entryPath = _ref.entryPath,
32
+ var entryName = _ref.entryName,
33
+ entryPath = _ref.entryPath,
33
34
  fileName = _ref.fileName;
34
35
  var entryFiles = [];
35
36
  var htmlFilePath;
@@ -78,7 +79,9 @@ var addEntry = function addEntry(_ref) {
78
79
  buildStart: function buildStart() {
79
80
  var _this$emitFile;
80
81
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
81
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
82
+ this.emitFile((_this$emitFile = {
83
+ name: entryName
84
+ }, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
82
85
  if (htmlFilePath) {
83
86
  var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
84
87
  var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
@@ -149,10 +152,18 @@ function normalizeRemoteItem(key, remote) {
149
152
  entryGlobalName: key
150
153
  }, remote);
151
154
  }
155
+ function removePathFromNpmPackage(packageString) {
156
+ // 匹配npm包名的正则表达式,忽略路径部分
157
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
158
+ // 使用正则表达式匹配并提取包名
159
+ var match = packageString.match(regex);
160
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
161
+ return match ? match[0] : packageString;
162
+ }
152
163
  function normalizeShareItem(key, shareItem) {
153
164
  var version;
154
165
  try {
155
- version = require(path__namespace.join(key, 'package.json')).version;
166
+ version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
156
167
  } catch (e) {
157
168
  console.log(e);
158
169
  }
@@ -256,6 +267,7 @@ function writeLocalSharedImportMap(pkgList) {
256
267
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
257
268
  }).join(",") + "\n }\n ");
258
269
  }
270
+ var LOAD_SHARE_TAG = "__mf__loadShare_";
259
271
  /**
260
272
  * generate loadShare virtual module
261
273
  */
@@ -263,7 +275,7 @@ var cacheMap1 = {};
263
275
  function getLoadShareModulePath(pkg) {
264
276
  var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
265
277
  name = _getNormalizeModuleFe2.name;
266
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
278
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("" + LOAD_SHARE_TAG + npmPackageNameToFileName(pkg) + ".js");
267
279
  var filename = cacheMap1[pkg];
268
280
  return path.resolve(emptyNpmDir, filename);
269
281
  }
@@ -280,7 +292,7 @@ function npmPackageNameToFileName(packageName) {
280
292
  }
281
293
 
282
294
  var emptyPath = require.resolve('an-empty-js-file');
283
- var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
295
+ var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
284
296
  function generateRemoteEntry(options) {
285
297
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
286
298
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -291,7 +303,7 @@ function generateRemoteEntry(options) {
291
303
  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 ";
292
304
  }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
293
305
  var shareItem = options.shared[key];
294
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
306
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \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 ";
295
307
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
296
308
  var remote = options.remotes[key];
297
309
  return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n }\n ";
@@ -299,7 +311,7 @@ function generateRemoteEntry(options) {
299
311
  return item[0] + "()";
300
312
  }).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 ";
301
313
  }
302
- var WRAP_REMOTE_ENTRY_QUERY_STR = "__mf__wrapRemoteEntry__";
314
+ var WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
303
315
  var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
304
316
  function generateWrapRemoteEntry() {
305
317
  return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
@@ -308,7 +320,7 @@ function generateWrapRemoteEntry() {
308
320
  * Inject entry file, automatically init when used as host,
309
321
  * and will not inject remoteEntry
310
322
  */
311
- var HOST_AUTO_INIT_QUERY_STR = "__mf__isHostInit";
323
+ var HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
312
324
  var HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
313
325
  function generateWrapHostInit() {
314
326
  return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
@@ -405,6 +417,24 @@ function pluginProxyRemotes (options) {
405
417
  };
406
418
  }
407
419
 
420
+ function wrapManualChunks(output, manualChunksCb) {
421
+ if (!output.manualChunks) output.manualChunks = {};
422
+ var wrapManualChunks = function wrapManualChunks(original) {
423
+ return function (id) {
424
+ var args = [].slice.call(arguments, 1);
425
+ var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
426
+ if (customRes) return customRes;
427
+ if (typeof original === 'function') {
428
+ return original.apply(void 0, [id].concat(args));
429
+ }
430
+ if (typeof original === 'object' && original) {
431
+ return original[id];
432
+ }
433
+ };
434
+ };
435
+ output.manualChunks = wrapManualChunks(output.manualChunks);
436
+ }
437
+
408
438
  function proxySharedModule(options) {
409
439
  var _options$shared = options.shared,
410
440
  shared = _options$shared === void 0 ? {} : _options$shared,
@@ -418,29 +448,47 @@ function proxySharedModule(options) {
418
448
  config: function config(_config, _ref) {
419
449
  var _config$resolve$alias, _config$resolve$alias2;
420
450
  var command = _ref.command;
451
+ if (!_config.build) _config.build = {};
452
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
453
+ var rollupOptions = _config.build.rollupOptions;
454
+ if (!rollupOptions.output) rollupOptions.output = {};
421
455
  // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
422
456
  // config.optimizeDeps.needsInterop.push('an-empty-js-file');
457
+ wrapManualChunks(_config.build.rollupOptions.output, function (id) {
458
+ if (id.includes("node_modules/@module-federation/runtime")) {
459
+ return "@module-federation/runtime";
460
+ }
461
+ if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
462
+ return id.split("/").pop();
463
+ }
464
+ });
423
465
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
424
- var _config$optimizeDeps;
466
+ var _config$optimizeDeps, _config$optimizeDeps2;
425
467
  _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
426
468
  // write proxyFile
427
469
  writeLoadShareModule(key, shared[key], command);
428
470
  var preBuildLibPath = getLoadShareModulePath(key);
471
+ _config == null || (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
429
472
  return {
430
473
  // Intercept all dependency requests to the proxy module
431
474
  // Dependency requests issued by localSharedImportMap are allowed without proxying.
432
475
  find: new RegExp("^" + key + "$"),
433
476
  replacement: preBuildLibPath,
434
477
  customResolver: function customResolver(source, importer) {
478
+ var _config$optimizeDeps3;
435
479
  if (importer.includes("node_modules/" + key + "/")) {
436
480
  return this.resolve(key);
437
481
  }
482
+ _config == null || (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
438
483
  return this.resolve(preBuildLibPath);
439
484
  }
440
485
  };
441
486
  }));
442
487
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
443
- return {
488
+ return command === "build" ? {
489
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
490
+ replacement: key
491
+ } : {
444
492
  find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
445
493
  customResolver: function customResolver(source, importer) {
446
494
  return this.resolve(key);
@@ -535,39 +583,6 @@ var aliasToArrayPlugin = {
535
583
  }
536
584
  };
537
585
 
538
- var normalizeBuildPlugin = (function (singleChunkModules) {
539
- return {
540
- name: 'normalizeBuild',
541
- config: function config(_config, _ref) {
542
- if (!_config.build) _config.build = {};
543
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
544
- var rollupOptions = _config.build.rollupOptions;
545
- if (!rollupOptions.output) rollupOptions.output = {};
546
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
547
- }
548
- };
549
- });
550
- function normalizeManualChunks(output, singleChunkModules) {
551
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
552
- if (!output.manualChunks) output.manualChunks = {};
553
- var wrapManualChunks = function wrapManualChunks(original) {
554
- return function (id) {
555
- var _ref2 = id.match(pattern) || [],
556
- moduleName = _ref2[1];
557
- if (moduleName) {
558
- return moduleName;
559
- }
560
- if (typeof original === 'function') {
561
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
562
- }
563
- if (typeof original === 'object' && original) {
564
- return original[id];
565
- }
566
- };
567
- };
568
- output.manualChunks = wrapManualChunks(output.manualChunks);
569
- }
570
-
571
586
  var normalizeOptimizeDepsPlugin = {
572
587
  name: 'normalizeOptimizeDeps',
573
588
  config: function config(_config, _ref) {
@@ -587,7 +602,7 @@ function federation(mfUserOptions) {
587
602
  shared = options.shared,
588
603
  filename = options.filename;
589
604
  if (!name) throw new Error("name is required");
590
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
605
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
591
606
  entryName: 'remoteEntry',
592
607
  entryPath: WRAP_REMOTE_ENTRY_PATH,
593
608
  fileName: filename
package/lib/index.esm.js CHANGED
@@ -7,7 +7,8 @@ import { walk } from 'estree-walker';
7
7
  import MagicString from 'magic-string';
8
8
 
9
9
  var addEntry = function addEntry(_ref) {
10
- var entryPath = _ref.entryPath,
10
+ var entryName = _ref.entryName,
11
+ entryPath = _ref.entryPath,
11
12
  fileName = _ref.fileName;
12
13
  var entryFiles = [];
13
14
  var htmlFilePath;
@@ -56,7 +57,9 @@ var addEntry = function addEntry(_ref) {
56
57
  buildStart: function buildStart() {
57
58
  var _this$emitFile;
58
59
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
59
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
60
+ this.emitFile((_this$emitFile = {
61
+ name: entryName
62
+ }, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
60
63
  if (htmlFilePath) {
61
64
  var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
62
65
  var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
@@ -127,10 +130,18 @@ function normalizeRemoteItem(key, remote) {
127
130
  entryGlobalName: key
128
131
  }, remote);
129
132
  }
133
+ function removePathFromNpmPackage(packageString) {
134
+ // 匹配npm包名的正则表达式,忽略路径部分
135
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
136
+ // 使用正则表达式匹配并提取包名
137
+ var match = packageString.match(regex);
138
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
139
+ return match ? match[0] : packageString;
140
+ }
130
141
  function normalizeShareItem(key, shareItem) {
131
142
  var version;
132
143
  try {
133
- version = require(path.join(key, 'package.json')).version;
144
+ version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
134
145
  } catch (e) {
135
146
  console.log(e);
136
147
  }
@@ -234,6 +245,7 @@ function writeLocalSharedImportMap(pkgList) {
234
245
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
235
246
  }).join(",") + "\n }\n ");
236
247
  }
248
+ var LOAD_SHARE_TAG = "__mf__loadShare_";
237
249
  /**
238
250
  * generate loadShare virtual module
239
251
  */
@@ -241,7 +253,7 @@ var cacheMap1 = {};
241
253
  function getLoadShareModulePath(pkg) {
242
254
  var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
243
255
  name = _getNormalizeModuleFe2.name;
244
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
256
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("" + LOAD_SHARE_TAG + npmPackageNameToFileName(pkg) + ".js");
245
257
  var filename = cacheMap1[pkg];
246
258
  return resolve(emptyNpmDir, filename);
247
259
  }
@@ -258,7 +270,7 @@ function npmPackageNameToFileName(packageName) {
258
270
  }
259
271
 
260
272
  var emptyPath = require.resolve('an-empty-js-file');
261
- var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
273
+ var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
262
274
  function generateRemoteEntry(options) {
263
275
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
264
276
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -269,7 +281,7 @@ function generateRemoteEntry(options) {
269
281
  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 ";
270
282
  }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
271
283
  var shareItem = options.shared[key];
272
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
284
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \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 ";
273
285
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
274
286
  var remote = options.remotes[key];
275
287
  return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n }\n ";
@@ -277,7 +289,7 @@ function generateRemoteEntry(options) {
277
289
  return item[0] + "()";
278
290
  }).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 ";
279
291
  }
280
- var WRAP_REMOTE_ENTRY_QUERY_STR = "__mf__wrapRemoteEntry__";
292
+ var WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
281
293
  var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
282
294
  function generateWrapRemoteEntry() {
283
295
  return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
@@ -286,7 +298,7 @@ function generateWrapRemoteEntry() {
286
298
  * Inject entry file, automatically init when used as host,
287
299
  * and will not inject remoteEntry
288
300
  */
289
- var HOST_AUTO_INIT_QUERY_STR = "__mf__isHostInit";
301
+ var HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
290
302
  var HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
291
303
  function generateWrapHostInit() {
292
304
  return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
@@ -383,6 +395,24 @@ function pluginProxyRemotes (options) {
383
395
  };
384
396
  }
385
397
 
398
+ function wrapManualChunks(output, manualChunksCb) {
399
+ if (!output.manualChunks) output.manualChunks = {};
400
+ var wrapManualChunks = function wrapManualChunks(original) {
401
+ return function (id) {
402
+ var args = [].slice.call(arguments, 1);
403
+ var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
404
+ if (customRes) return customRes;
405
+ if (typeof original === 'function') {
406
+ return original.apply(void 0, [id].concat(args));
407
+ }
408
+ if (typeof original === 'object' && original) {
409
+ return original[id];
410
+ }
411
+ };
412
+ };
413
+ output.manualChunks = wrapManualChunks(output.manualChunks);
414
+ }
415
+
386
416
  function proxySharedModule(options) {
387
417
  var _options$shared = options.shared,
388
418
  shared = _options$shared === void 0 ? {} : _options$shared,
@@ -396,29 +426,47 @@ function proxySharedModule(options) {
396
426
  config: function config(_config, _ref) {
397
427
  var _config$resolve$alias, _config$resolve$alias2;
398
428
  var command = _ref.command;
429
+ if (!_config.build) _config.build = {};
430
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
431
+ var rollupOptions = _config.build.rollupOptions;
432
+ if (!rollupOptions.output) rollupOptions.output = {};
399
433
  // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
400
434
  // config.optimizeDeps.needsInterop.push('an-empty-js-file');
435
+ wrapManualChunks(_config.build.rollupOptions.output, function (id) {
436
+ if (id.includes("node_modules/@module-federation/runtime")) {
437
+ return "@module-federation/runtime";
438
+ }
439
+ if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
440
+ return id.split("/").pop();
441
+ }
442
+ });
401
443
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
402
- var _config$optimizeDeps;
444
+ var _config$optimizeDeps, _config$optimizeDeps2;
403
445
  _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
404
446
  // write proxyFile
405
447
  writeLoadShareModule(key, shared[key], command);
406
448
  var preBuildLibPath = getLoadShareModulePath(key);
449
+ _config == null || (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
407
450
  return {
408
451
  // Intercept all dependency requests to the proxy module
409
452
  // Dependency requests issued by localSharedImportMap are allowed without proxying.
410
453
  find: new RegExp("^" + key + "$"),
411
454
  replacement: preBuildLibPath,
412
455
  customResolver: function customResolver(source, importer) {
456
+ var _config$optimizeDeps3;
413
457
  if (importer.includes("node_modules/" + key + "/")) {
414
458
  return this.resolve(key);
415
459
  }
460
+ _config == null || (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
416
461
  return this.resolve(preBuildLibPath);
417
462
  }
418
463
  };
419
464
  }));
420
465
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
421
- return {
466
+ return command === "build" ? {
467
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
468
+ replacement: key
469
+ } : {
422
470
  find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
423
471
  customResolver: function customResolver(source, importer) {
424
472
  return this.resolve(key);
@@ -513,39 +561,6 @@ var aliasToArrayPlugin = {
513
561
  }
514
562
  };
515
563
 
516
- var normalizeBuildPlugin = (function (singleChunkModules) {
517
- return {
518
- name: 'normalizeBuild',
519
- config: function config(_config, _ref) {
520
- if (!_config.build) _config.build = {};
521
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
522
- var rollupOptions = _config.build.rollupOptions;
523
- if (!rollupOptions.output) rollupOptions.output = {};
524
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
525
- }
526
- };
527
- });
528
- function normalizeManualChunks(output, singleChunkModules) {
529
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
530
- if (!output.manualChunks) output.manualChunks = {};
531
- var wrapManualChunks = function wrapManualChunks(original) {
532
- return function (id) {
533
- var _ref2 = id.match(pattern) || [],
534
- moduleName = _ref2[1];
535
- if (moduleName) {
536
- return moduleName;
537
- }
538
- if (typeof original === 'function') {
539
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
540
- }
541
- if (typeof original === 'object' && original) {
542
- return original[id];
543
- }
544
- };
545
- };
546
- output.manualChunks = wrapManualChunks(output.manualChunks);
547
- }
548
-
549
564
  var normalizeOptimizeDepsPlugin = {
550
565
  name: 'normalizeOptimizeDeps',
551
566
  config: function config(_config, _ref) {
@@ -565,7 +580,7 @@ function federation(mfUserOptions) {
565
580
  shared = options.shared,
566
581
  filename = options.filename;
567
582
  if (!name) throw new Error("name is required");
568
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
583
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
569
584
  entryName: 'remoteEntry',
570
585
  entryPath: WRAP_REMOTE_ENTRY_PATH,
571
586
  fileName: filename
@@ -60,6 +60,7 @@ const addEntry = ({
60
60
  buildStart() {
61
61
  const hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
62
62
  this.emitFile({
63
+ name: entryName,
63
64
  [hasHash ? "name" : "fileName"]: fileName,
64
65
  type: 'chunk',
65
66
  id: entryPath,
@@ -134,10 +135,18 @@ function normalizeRemoteItem(key, remote) {
134
135
  entryGlobalName: key
135
136
  }, remote);
136
137
  }
138
+ function removePathFromNpmPackage(packageString) {
139
+ // 匹配npm包名的正则表达式,忽略路径部分
140
+ const regex = /^(?:@[^/]+\/)?[^/]+/;
141
+ // 使用正则表达式匹配并提取包名
142
+ const match = packageString.match(regex);
143
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
144
+ return match ? match[0] : packageString;
145
+ }
137
146
  function normalizeShareItem(key, shareItem) {
138
147
  let version;
139
148
  try {
140
- version = require(path.join(key, 'package.json')).version;
149
+ version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
141
150
  } catch (e) {
142
151
  console.log(e);
143
152
  }
@@ -249,6 +258,7 @@ function writeLocalSharedImportMap(pkgList) {
249
258
  }
250
259
  `);
251
260
  }
261
+ const LOAD_SHARE_TAG = "__mf__loadShare_";
252
262
  /**
253
263
  * generate loadShare virtual module
254
264
  */
@@ -257,7 +267,7 @@ function getLoadShareModulePath(pkg) {
257
267
  const {
258
268
  name
259
269
  } = getNormalizeModuleFederationOptions();
260
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + `__mf__loadShare_${npmPackageNameToFileName(pkg)}.js`;
270
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + `${LOAD_SHARE_TAG}${npmPackageNameToFileName(pkg)}.js`;
261
271
  const filename = cacheMap1[pkg];
262
272
  return resolve(emptyNpmDir, filename);
263
273
  }
@@ -286,7 +296,7 @@ function npmPackageNameToFileName(packageName) {
286
296
  }
287
297
 
288
298
  const emptyPath = require.resolve('an-empty-js-file');
289
- const REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
299
+ const REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
290
300
  function generateRemoteEntry(options) {
291
301
  const pluginImportNames = options.runtimePlugins.map((p, i) => [`$runtimePlugin_${i}`, `import $runtimePlugin_${i} from "${p}";`]);
292
302
  return `
@@ -326,8 +336,14 @@ function generateRemoteEntry(options) {
326
336
  localShared[${JSON.stringify(key)}].loaded = true
327
337
  const {${JSON.stringify(key)}: pkgDynamicImport} = localSharedImportMap
328
338
  const res = await pkgDynamicImport()
339
+ const exportModule = {...res}
340
+ // All npm packages pre-built by vite will be converted to esm
341
+ Object.defineProperty(exportModule, "__esModule", {
342
+ value: true,
343
+ enumerable: false
344
+ })
329
345
  return function () {
330
- return res
346
+ return exportModule
331
347
  }
332
348
  },
333
349
  shareConfig: {
@@ -369,7 +385,7 @@ function generateRemoteEntry(options) {
369
385
  }
370
386
  `;
371
387
  }
372
- const WRAP_REMOTE_ENTRY_QUERY_STR = "__mf__wrapRemoteEntry__";
388
+ const WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
373
389
  const WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
374
390
  function generateWrapRemoteEntry() {
375
391
  return `
@@ -381,7 +397,7 @@ function generateWrapRemoteEntry() {
381
397
  * Inject entry file, automatically init when used as host,
382
398
  * and will not inject remoteEntry
383
399
  */
384
- const HOST_AUTO_INIT_QUERY_STR = "__mf__isHostInit";
400
+ const HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
385
401
  const HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
386
402
  function generateWrapHostInit() {
387
403
  return `
@@ -480,6 +496,21 @@ function pluginProxyRemotes (options) {
480
496
  };
481
497
  }
482
498
 
499
+ function wrapManualChunks(output, manualChunksCb) {
500
+ if (!output.manualChunks) output.manualChunks = {};
501
+ const wrapManualChunks = original => (id, ...args) => {
502
+ const customRes = manualChunksCb == null ? void 0 : manualChunksCb(id, ...args);
503
+ if (customRes) return customRes;
504
+ if (typeof original === 'function') {
505
+ return original(id, ...args);
506
+ }
507
+ if (typeof original === 'object' && original) {
508
+ return original[id];
509
+ }
510
+ };
511
+ output.manualChunks = wrapManualChunks(output.manualChunks);
512
+ }
513
+
483
514
  function proxySharedModule(options) {
484
515
  let {
485
516
  shared = {},
@@ -494,29 +525,49 @@ function proxySharedModule(options) {
494
525
  config(config, {
495
526
  command
496
527
  }) {
528
+ if (!config.build) config.build = {};
529
+ if (!config.build.rollupOptions) config.build.rollupOptions = {};
530
+ let {
531
+ rollupOptions
532
+ } = config.build;
533
+ if (!rollupOptions.output) rollupOptions.output = {};
497
534
  // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
498
535
  // config.optimizeDeps.needsInterop.push('an-empty-js-file');
536
+ wrapManualChunks(config.build.rollupOptions.output, id => {
537
+ if (id.includes("node_modules/@module-federation/runtime")) {
538
+ return "@module-federation/runtime";
539
+ }
540
+ if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
541
+ return id.split("/").pop();
542
+ }
543
+ });
499
544
  config.resolve.alias.push(...Object.keys(shared).map(key => {
500
- var _config$optimizeDeps;
545
+ var _config$optimizeDeps, _config$optimizeDeps2;
501
546
  config == null || (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
502
547
  // write proxyFile
503
548
  writeLoadShareModule(key, shared[key], command);
504
549
  const preBuildLibPath = getLoadShareModulePath(key);
550
+ config == null || (_config$optimizeDeps2 = config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
505
551
  return {
506
552
  // Intercept all dependency requests to the proxy module
507
553
  // Dependency requests issued by localSharedImportMap are allowed without proxying.
508
554
  find: new RegExp(`^${key}$`),
509
555
  replacement: preBuildLibPath,
510
556
  customResolver(source, importer) {
557
+ var _config$optimizeDeps3;
511
558
  if (importer.includes(`node_modules/${key}/`)) {
512
559
  return this.resolve(key);
513
560
  }
561
+ config == null || (_config$optimizeDeps3 = config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
514
562
  return this.resolve(preBuildLibPath);
515
563
  }
516
564
  };
517
565
  }));
518
566
  config.resolve.alias.push(...Object.keys(shared).map(key => {
519
- return {
567
+ return command === "build" ? {
568
+ find: new RegExp(`^${getPreBuildLibPath(key)}$`),
569
+ replacement: key
570
+ } : {
520
571
  find: new RegExp(`^${getPreBuildLibPath(key)}$`),
521
572
  customResolver(source, importer) {
522
573
  return this.resolve(key);
@@ -617,38 +668,6 @@ var aliasToArrayPlugin = {
617
668
  }
618
669
  };
619
670
 
620
- var normalizeBuildPlugin = (singleChunkModules => ({
621
- name: 'normalizeBuild',
622
- config: (config, {
623
- command
624
- }) => {
625
- if (!config.build) config.build = {};
626
- if (!config.build.rollupOptions) config.build.rollupOptions = {};
627
- let {
628
- rollupOptions
629
- } = config.build;
630
- if (!rollupOptions.output) rollupOptions.output = {};
631
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
632
- }
633
- }));
634
- function normalizeManualChunks(output, singleChunkModules) {
635
- const pattern = new RegExp(`node_modules/(${singleChunkModules.join('|')})/`);
636
- if (!output.manualChunks) output.manualChunks = {};
637
- const wrapManualChunks = original => (id, ...args) => {
638
- const [_, moduleName] = id.match(pattern) || [];
639
- if (moduleName) {
640
- return moduleName;
641
- }
642
- if (typeof original === 'function') {
643
- return original(id, ...args);
644
- }
645
- if (typeof original === 'object' && original) {
646
- return original[id];
647
- }
648
- };
649
- output.manualChunks = wrapManualChunks(output.manualChunks);
650
- }
651
-
652
671
  var normalizeOptimizeDepsPlugin = {
653
672
  name: 'normalizeOptimizeDeps',
654
673
  config: (config, {
@@ -675,7 +694,7 @@ function federation(mfUserOptions) {
675
694
  filename
676
695
  } = options;
677
696
  if (!name) throw new Error("name is required");
678
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([...Object.keys(shared), "@module-federation/runtime"]), ...addEntry({
697
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, ...addEntry({
679
698
  entryName: 'remoteEntry',
680
699
  entryPath: WRAP_REMOTE_ENTRY_PATH,
681
700
  fileName: filename
package/lib/index.umd.js CHANGED
@@ -28,7 +28,8 @@
28
28
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
29
29
 
30
30
  var addEntry = function addEntry(_ref) {
31
- var entryPath = _ref.entryPath,
31
+ var entryName = _ref.entryName,
32
+ entryPath = _ref.entryPath,
32
33
  fileName = _ref.fileName;
33
34
  var entryFiles = [];
34
35
  var htmlFilePath;
@@ -77,7 +78,9 @@
77
78
  buildStart: function buildStart() {
78
79
  var _this$emitFile;
79
80
  var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
80
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
81
+ this.emitFile((_this$emitFile = {
82
+ name: entryName
83
+ }, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
81
84
  if (htmlFilePath) {
82
85
  var htmlContent = fs__namespace.readFileSync(htmlFilePath, 'utf-8');
83
86
  var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
@@ -148,10 +151,18 @@
148
151
  entryGlobalName: key
149
152
  }, remote);
150
153
  }
154
+ function removePathFromNpmPackage(packageString) {
155
+ // 匹配npm包名的正则表达式,忽略路径部分
156
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
157
+ // 使用正则表达式匹配并提取包名
158
+ var match = packageString.match(regex);
159
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
160
+ return match ? match[0] : packageString;
161
+ }
151
162
  function normalizeShareItem(key, shareItem) {
152
163
  var version;
153
164
  try {
154
- version = require(path__namespace.join(key, 'package.json')).version;
165
+ version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
155
166
  } catch (e) {
156
167
  console.log(e);
157
168
  }
@@ -255,6 +266,7 @@
255
266
  return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
256
267
  }).join(",") + "\n }\n ");
257
268
  }
269
+ var LOAD_SHARE_TAG = "__mf__loadShare_";
258
270
  /**
259
271
  * generate loadShare virtual module
260
272
  */
@@ -262,7 +274,7 @@
262
274
  function getLoadShareModulePath(pkg) {
263
275
  var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
264
276
  name = _getNormalizeModuleFe2.name;
265
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
277
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("" + LOAD_SHARE_TAG + npmPackageNameToFileName(pkg) + ".js");
266
278
  var filename = cacheMap1[pkg];
267
279
  return path.resolve(emptyNpmDir, filename);
268
280
  }
@@ -279,7 +291,7 @@
279
291
  }
280
292
 
281
293
  var emptyPath = require.resolve('an-empty-js-file');
282
- var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
294
+ var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
283
295
  function generateRemoteEntry(options) {
284
296
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
285
297
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -290,7 +302,7 @@
290
302
  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 ";
291
303
  }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
292
304
  var shareItem = options.shared[key];
293
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
305
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\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 localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \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 ";
294
306
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
295
307
  var remote = options.remotes[key];
296
308
  return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n }\n ";
@@ -298,7 +310,7 @@
298
310
  return item[0] + "()";
299
311
  }).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 ";
300
312
  }
301
- var WRAP_REMOTE_ENTRY_QUERY_STR = "__mf__wrapRemoteEntry__";
313
+ var WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
302
314
  var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
303
315
  function generateWrapRemoteEntry() {
304
316
  return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
@@ -307,7 +319,7 @@
307
319
  * Inject entry file, automatically init when used as host,
308
320
  * and will not inject remoteEntry
309
321
  */
310
- var HOST_AUTO_INIT_QUERY_STR = "__mf__isHostInit";
322
+ var HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
311
323
  var HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
312
324
  function generateWrapHostInit() {
313
325
  return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
@@ -404,6 +416,24 @@
404
416
  };
405
417
  }
406
418
 
419
+ function wrapManualChunks(output, manualChunksCb) {
420
+ if (!output.manualChunks) output.manualChunks = {};
421
+ var wrapManualChunks = function wrapManualChunks(original) {
422
+ return function (id) {
423
+ var args = [].slice.call(arguments, 1);
424
+ var customRes = manualChunksCb == null ? void 0 : manualChunksCb.apply(void 0, [id].concat(args));
425
+ if (customRes) return customRes;
426
+ if (typeof original === 'function') {
427
+ return original.apply(void 0, [id].concat(args));
428
+ }
429
+ if (typeof original === 'object' && original) {
430
+ return original[id];
431
+ }
432
+ };
433
+ };
434
+ output.manualChunks = wrapManualChunks(output.manualChunks);
435
+ }
436
+
407
437
  function proxySharedModule(options) {
408
438
  var _options$shared = options.shared,
409
439
  shared = _options$shared === void 0 ? {} : _options$shared,
@@ -417,29 +447,47 @@
417
447
  config: function config(_config, _ref) {
418
448
  var _config$resolve$alias, _config$resolve$alias2;
419
449
  var command = _ref.command;
450
+ if (!_config.build) _config.build = {};
451
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
452
+ var rollupOptions = _config.build.rollupOptions;
453
+ if (!rollupOptions.output) rollupOptions.output = {};
420
454
  // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
421
455
  // config.optimizeDeps.needsInterop.push('an-empty-js-file');
456
+ wrapManualChunks(_config.build.rollupOptions.output, function (id) {
457
+ if (id.includes("node_modules/@module-federation/runtime")) {
458
+ return "@module-federation/runtime";
459
+ }
460
+ if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
461
+ return id.split("/").pop();
462
+ }
463
+ });
422
464
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
423
- var _config$optimizeDeps;
465
+ var _config$optimizeDeps, _config$optimizeDeps2;
424
466
  _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
425
467
  // write proxyFile
426
468
  writeLoadShareModule(key, shared[key], command);
427
469
  var preBuildLibPath = getLoadShareModulePath(key);
470
+ _config == null || (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
428
471
  return {
429
472
  // Intercept all dependency requests to the proxy module
430
473
  // Dependency requests issued by localSharedImportMap are allowed without proxying.
431
474
  find: new RegExp("^" + key + "$"),
432
475
  replacement: preBuildLibPath,
433
476
  customResolver: function customResolver(source, importer) {
477
+ var _config$optimizeDeps3;
434
478
  if (importer.includes("node_modules/" + key + "/")) {
435
479
  return this.resolve(key);
436
480
  }
481
+ _config == null || (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
437
482
  return this.resolve(preBuildLibPath);
438
483
  }
439
484
  };
440
485
  }));
441
486
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
442
- return {
487
+ return command === "build" ? {
488
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
489
+ replacement: key
490
+ } : {
443
491
  find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
444
492
  customResolver: function customResolver(source, importer) {
445
493
  return this.resolve(key);
@@ -534,39 +582,6 @@
534
582
  }
535
583
  };
536
584
 
537
- var normalizeBuildPlugin = (function (singleChunkModules) {
538
- return {
539
- name: 'normalizeBuild',
540
- config: function config(_config, _ref) {
541
- if (!_config.build) _config.build = {};
542
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
543
- var rollupOptions = _config.build.rollupOptions;
544
- if (!rollupOptions.output) rollupOptions.output = {};
545
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
546
- }
547
- };
548
- });
549
- function normalizeManualChunks(output, singleChunkModules) {
550
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
551
- if (!output.manualChunks) output.manualChunks = {};
552
- var wrapManualChunks = function wrapManualChunks(original) {
553
- return function (id) {
554
- var _ref2 = id.match(pattern) || [],
555
- moduleName = _ref2[1];
556
- if (moduleName) {
557
- return moduleName;
558
- }
559
- if (typeof original === 'function') {
560
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
561
- }
562
- if (typeof original === 'object' && original) {
563
- return original[id];
564
- }
565
- };
566
- };
567
- output.manualChunks = wrapManualChunks(output.manualChunks);
568
- }
569
-
570
585
  var normalizeOptimizeDepsPlugin = {
571
586
  name: 'normalizeOptimizeDeps',
572
587
  config: function config(_config, _ref) {
@@ -586,7 +601,7 @@
586
601
  shared = options.shared,
587
602
  filename = options.filename;
588
603
  if (!name) throw new Error("name is required");
589
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
604
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin].concat(addEntry({
590
605
  entryName: 'remoteEntry',
591
606
  entryPath: WRAP_REMOTE_ENTRY_PATH,
592
607
  fileName: filename
@@ -0,0 +1 @@
1
+ export declare function wrapManualChunks(output: any, manualChunksCb: Function): void;
@@ -1,4 +1,4 @@
1
- import { NormalizedModuleFederationOptions } from "../utils/normalizeModuleFederationOptions";
1
+ import { NormalizedModuleFederationOptions } from '../utils/normalizeModuleFederationOptions';
2
2
  export declare const REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
3
3
  export declare function generateRemoteEntry(options: NormalizedModuleFederationOptions): string;
4
4
  export declare const WRAP_REMOTE_ENTRY_QUERY_STR = "__mf__wrapRemoteEntry__";
@@ -8,5 +8,6 @@ export declare function getPreBuildLibPath(pkg: string): string;
8
8
  export declare function getLocalSharedImportMapId(): string;
9
9
  export declare function getLocalSharedImportMapPath(): string;
10
10
  export declare function writeLocalSharedImportMap(pkgList: string[]): void;
11
+ export declare const LOAD_SHARE_TAG = "__mf__loadShare_";
11
12
  export declare function getLoadShareModulePath(pkg: string): string;
12
13
  export declare function writeLoadShareModule(pkg: string, shareItem: ShareItem, command: string): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.0.0-alpha-10e1f83",
3
+ "version": "1.0.0-alpha-51eeeb6",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "source": "src/index.ts",
@@ -38,7 +38,7 @@
38
38
  "homepage": "https://github.com/module-federation/vite#readme",
39
39
  "packageManager": "pnpm@9.1.3",
40
40
  "dependencies": {
41
- "@module-federation/runtime": "^0.3.5",
41
+ "@module-federation/runtime": "^0.5.0",
42
42
  "@rollup/pluginutils": "^5.1.0",
43
43
  "an-empty-js-file": "1.0.0",
44
44
  "estree-walker": "^2",
@@ -51,6 +51,6 @@
51
51
  "mime-types": "^2.1.35",
52
52
  "pretty-quick": "^4.0.0",
53
53
  "rimraf": "^6.0.1",
54
- "vite": "^5.4.0"
54
+ "vite": "^5.4.1"
55
55
  }
56
56
  }
@@ -1,8 +0,0 @@
1
- import { UserConfig } from 'vite';
2
- declare const _default: (singleChunkModules: string[]) => {
3
- name: string;
4
- config: (config: UserConfig, { command }: {
5
- command: string;
6
- }) => void;
7
- };
8
- export default _default;