@module-federation/vite 1.20.6 → 1.20.7

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.
Files changed (2) hide show
  1. package/lib/index.js +150 -88
  2. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -1084,12 +1084,56 @@ function generateExposes(options, remoteDependencyMap = {}, command = "build", r
1084
1084
  `;
1085
1085
  }
1086
1086
  //#endregion
1087
+ //#region src/utils/sharedExportConditions.ts
1088
+ const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
1089
+ "browser",
1090
+ "import",
1091
+ "module",
1092
+ "default"
1093
+ ];
1094
+ const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
1095
+ "node",
1096
+ "import",
1097
+ "module",
1098
+ "default"
1099
+ ];
1100
+ const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
1101
+ "worker",
1102
+ "browser",
1103
+ "import",
1104
+ "module",
1105
+ "default"
1106
+ ];
1107
+ const VITE_DEV_PROD_CONDITION = "development|production";
1108
+ function appendConditions(conditions, fallbackConditions) {
1109
+ return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
1110
+ }
1111
+ function resolveViteModeCondition(conditions, isProduction) {
1112
+ const modeCondition = isProduction ? "production" : "development";
1113
+ return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
1114
+ }
1115
+ function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
1116
+ if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
1117
+ const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
1118
+ const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
1119
+ if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
1120
+ return [...defaultConditions];
1121
+ }
1122
+ function isReactServerConditions(conditions) {
1123
+ return Boolean(conditions?.includes("react-server"));
1124
+ }
1125
+ //#endregion
1087
1126
  //#region src/virtualModules/virtualRuntimeInitStatus.ts
1088
1127
  const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
1089
1128
  const runtimeInitModules = /* @__PURE__ */ new WeakMap();
1090
1129
  const runtimeInitOwnerIds = /* @__PURE__ */ new WeakMap();
1091
1130
  let nextRuntimeInitOwnerId = 1;
1092
1131
  const MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache__";
1132
+ const REACT_SERVER_MODULE_CACHE_GLOBAL_KEY = "__mf_module_cache_react_server__";
1133
+ const MODULE_CACHE_SHARE_SCOPE_KEY = "module-federation.vite-module-cache";
1134
+ function getModuleCacheGlobalKey(exportConditions) {
1135
+ return isReactServerConditions(exportConditions) ? REACT_SERVER_MODULE_CACHE_GLOBAL_KEY : MODULE_CACHE_GLOBAL_KEY;
1136
+ }
1093
1137
  function getRuntimeInitOwnerId(options) {
1094
1138
  let ownerId = runtimeInitOwnerIds.get(options);
1095
1139
  if (!ownerId) {
@@ -1173,10 +1217,10 @@ if (!${options.stateVar}) {
1173
1217
  const ${options.exposedConst} = ${options.stateVar}.${options.exposedProperty};
1174
1218
  `;
1175
1219
  }
1176
- function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId) {
1220
+ function getRuntimeInitBootstrapCode(enableSsrInit = false, ownerImportId, ssrRemotes, hostInitImportId = ownerImportId, exportConditions) {
1177
1221
  return `
1178
1222
  const globalKey = ${JSON.stringify(getRuntimeInitGlobalKey(ownerImportId))};
1179
- const moduleCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
1223
+ const moduleCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
1180
1224
  globalThis[moduleCacheGlobalKey] ||= { share: {}, remote: {} };
1181
1225
  globalThis[moduleCacheGlobalKey].share ||= {};
1182
1226
  globalThis[moduleCacheGlobalKey].remote ||= {};
@@ -1194,14 +1238,14 @@ if (${SERVER_ENV_GUARD} && !globalThis[globalKey].ssrInitStarted) {
1194
1238
  globalThis[globalKey].ssrInitStarted = true;
1195
1239
  ${getSsrNoopResolveCode(enableSsrInit, hostInitImportId, "globalThis[globalKey].initResolve", ssrRemotes)}
1196
1240
  }` : ""}
1197
- globalThis[globalKey].moduleCache ||= globalThis[moduleCacheGlobalKey];
1241
+ globalThis[globalKey].moduleCache = globalThis[moduleCacheGlobalKey];
1198
1242
  globalThis[globalKey].moduleCache.share ||= {};
1199
1243
  globalThis[globalKey].moduleCache.remote ||= {};
1200
1244
  `;
1201
1245
  }
1202
- function getRuntimeModuleCacheBootstrapCode() {
1246
+ function getRuntimeModuleCacheBootstrapCode(exportConditions) {
1203
1247
  return `
1204
- const __mfCacheGlobalKey = ${JSON.stringify(MODULE_CACHE_GLOBAL_KEY)};
1248
+ const __mfCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
1205
1249
  globalThis[__mfCacheGlobalKey] ||= { share: {}, remote: {} };
1206
1250
  globalThis[__mfCacheGlobalKey].share ||= {};
1207
1251
  globalThis[__mfCacheGlobalKey].remote ||= {};
@@ -2109,10 +2153,12 @@ function getNamedExportsViaRegex(source, filePath, visited, scanState = { comple
2109
2153
  const exportKeywordRegex = /\bexport\b/g;
2110
2154
  while ((match = exportKeywordRegex.exec(source)) !== null) {
2111
2155
  if (!codePositions[match.index]) continue;
2112
- if (!recognizedExportStarts.has(match.index)) {
2113
- scanState.complete = false;
2114
- break;
2115
- }
2156
+ if (recognizedExportStarts.has(match.index)) continue;
2157
+ let previousCodeIndex = match.index - 1;
2158
+ while (previousCodeIndex >= 0 && (/\s/.test(source[previousCodeIndex]) || !codePositions[previousCodeIndex])) previousCodeIndex--;
2159
+ if (source[previousCodeIndex] === ".") continue;
2160
+ scanState.complete = false;
2161
+ break;
2116
2162
  }
2117
2163
  return Array.from(names);
2118
2164
  }
@@ -2481,7 +2527,7 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
2481
2527
  });
2482
2528
  preBuildCacheMap[pkg].writeSync(`
2483
2529
  ${sharedCacheHelperCode}
2484
- const __mfCacheGlobalKey = "__mf_module_cache__";
2530
+ const __mfCacheGlobalKey = ${JSON.stringify(getModuleCacheGlobalKey(exportConditions))};
2485
2531
  export const c = function(size) {
2486
2532
  const cache = globalThis[__mfCacheGlobalKey]?.share;
2487
2533
  const sharedReact = cache && __mfReadSharedCache(cache, ${reactCacheDescriptor});
@@ -2545,12 +2591,12 @@ function writePreBuildLibPath(pkg, shareItem, options, exportConditions) {
2545
2591
  `, true);
2546
2592
  }
2547
2593
  /** Re-render already materialized wrappers after import analysis discovers exports. */
2548
- function refreshTreeShakingModules(options) {
2594
+ function refreshTreeShakingModules(options, command = "build", isRolldown = false, exportConditions) {
2549
2595
  const { preBuildShareItemMap } = getSharedVirtualModuleState(options);
2550
2596
  for (const [pkg, shareItem] of Object.entries(preBuildShareItemMap)) {
2551
2597
  if (!shareItem?.shareConfig.treeShaking) continue;
2552
- writePreBuildLibPath(pkg, shareItem, options);
2553
- writeLoadShareModule(pkg, shareItem, "build", false, options);
2598
+ writePreBuildLibPath(pkg, shareItem, options, exportConditions);
2599
+ writeLoadShareModule(pkg, shareItem, command, isRolldown, options, exportConditions);
2554
2600
  }
2555
2601
  }
2556
2602
  function getPreBuildLibImportId(pkg, options) {
@@ -2752,7 +2798,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2752
2798
  const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
2753
2799
  const { loadShareCacheMap } = getSharedVirtualModuleState(options);
2754
2800
  if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = createScopedSharedVirtualModule(pkg, LOAD_SHARE_TAG, options);
2755
- let importLine = getRuntimeModuleCacheBootstrapCode();
2801
+ let importLine = getRuntimeModuleCacheBootstrapCode(exportConditions);
2756
2802
  const cacheDescriptor = getSharedCacheDescriptorLiteral(pkg, shareItem);
2757
2803
  const cacheOwner = JSON.stringify(resolvedOptions.name);
2758
2804
  const runtimeInitOwnerImportId = options ? getRuntimeInitStatusImportId(options) : void 0;
@@ -2795,18 +2841,18 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2795
2841
  const servesRemoteSingletonFallback = command !== "build" && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true;
2796
2842
  const isConsumedByPeerSingleton = isSharedSingletonConsumedByPeer(pkg, resolvedOptions);
2797
2843
  const usesEntryInjectedRemoteFallback = hasCompleteExportCoverage && command !== "build" && !isWorkspaceSingleton && isRemoteOnlyContainer(resolvedOptions) && shareItem.shareConfig.singleton === true && resolvedOptions.hostInitInjectLocation === "entry" && isConsumedByPeerSingleton;
2798
- const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
2844
+ const usesEagerWorkspaceFallback = hasCompleteExportCoverage && isWorkspaceSingleton && !servesRemoteSingletonFallback && (isConsumedByPeerSingleton || shareItem.shareConfig.eager === true);
2799
2845
  const usesDeferredTreeShakingFallback = hasCompleteExportCoverage && Boolean(treeShakingConsumer);
2800
2846
  const reactMixedModeGuard = pkg === "react" ? createReactMixedModeRuntimeGuard() : "";
2801
2847
  let exportLine;
2802
2848
  let initBlock = "";
2803
2849
  if (usesDeferredTreeShakingFallback) {
2804
2850
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
2805
- exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
2851
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
2806
2852
  } else if (usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback) exportLine = generateEagerWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, liveNamedExports);
2807
2853
  else if (usesDeferredSingletonFallback) {
2808
2854
  importLine = `${getRuntimeInitPromiseBootstrapCode(false, runtimeInitOwnerImportId)}\n ${importLine}`;
2809
- exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && (isWorkspaceSingleton || isWorkspacePackage || servesRemoteSingletonFallback), liveNamedExports);
2855
+ exportLine = generateLazyWorkspaceSingletonExports(namedExports, lazyLocalFallbackSource, cacheDescriptor, cacheOwner, treeShakingConsumer, command !== "build" && !servesRemoteSingletonFallback && (isWorkspaceSingleton || isWorkspacePackage), liveNamedExports);
2810
2856
  } else if (detectedNamedExports === void 0) {
2811
2857
  exportLine = `const __mfDefaultExport = (() => {
2812
2858
  ${generateShareModuleUnwrapCode({
@@ -2875,7 +2921,7 @@ function writeLoadShareModule(pkg, shareItem, command, _isRolldown, options, exp
2875
2921
  initBlock = `exportModule = __mfNormalizeShareModule(__mfLocalShare);
2876
2922
  __mfWriteSharedCache(__mfModuleCache.share, ${cacheDescriptor}, exportModule, ${cacheOwner});`;
2877
2923
  }
2878
- const prebuildImportLine = usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? servesRemoteSingletonFallback || usesDeferredSingletonFallback && command !== "build" && (isWorkspaceSingleton || isWorkspacePackage) ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(lazyLocalFallbackSource)};` : "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(detectedNamedExports === void 0 ? coherentLocalSource : skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
2924
+ const prebuildImportLine = usesEagerWorkspaceFallback || usesEntryInjectedRemoteFallback ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? !servesRemoteSingletonFallback && usesDeferredSingletonFallback && command !== "build" && (isWorkspaceSingleton || isWorkspacePackage) ? `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(lazyLocalFallbackSource)};` : "" : `import * as __mfLocalShare from ${escapeGeneratedStringLiteral(detectedNamedExports === void 0 ? coherentLocalSource : skipServePrebuildWarmup ? devImportSource : sharedImportSource)};`;
2879
2925
  const devDynamicImportLine = isWorkspacePackage ? "" : usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? "" : command !== "build" && !skipServePrebuildWarmup ? `;() => import(${escapeGeneratedStringLiteral(devImportSource)}).catch(() => {});` : "";
2880
2926
  const moduleBody = usesDeferredSingletonFallback || usesDeferredTreeShakingFallback ? `
2881
2927
  ${prebuildImportLine}
@@ -3122,7 +3168,6 @@ function getMaterializedShares(options) {
3122
3168
  }
3123
3169
  }
3124
3170
  }
3125
- if (hasPackageDependency("vinext")) shares.delete("react");
3126
3171
  return orderSharedDependenciesFirst([...shares].sort((a, b) => {
3127
3172
  const priority = (pkg) => pkg === "react" ? 0 : pkg === "react-dom" ? 1 : pkg.startsWith("react/") ? 2 : 3;
3128
3173
  return priority(a) - priority(b) || a.localeCompare(b);
@@ -3689,7 +3734,7 @@ function generateTreeShakingSnapshotPluginCode(enabled) {
3689
3734
  },
3690
3735
  });`;
3691
3736
  }
3692
- function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build") {
3737
+ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(options), command = "build", exportConditions) {
3693
3738
  const needsSharedProviderSelectionHelper = Object.keys(options.shared ?? {}).length > 0;
3694
3739
  const hasTreeShakingShared = Object.values(options.shared ?? {}).some((share) => !!share?.shareConfig.treeShaking);
3695
3740
  const hasMultipleShareScopes = Array.isArray(options.shareScope);
@@ -3747,8 +3792,8 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
3747
3792
  import {${runtimeImports}} from "@module-federation/runtime";
3748
3793
  ${runtimeHelperImports.length ? `import {${runtimeHelperImports.join(", ")}} from "@module-federation/runtime/helpers";` : ""}
3749
3794
  ${pluginImportNames.filter((item) => !isSsrOnlyPlugin(item[1])).map((item) => item[1]).join("\n")}
3750
- ${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options)) + "\n const { initResolve } = globalThis[globalKey];"}
3751
- ${getRuntimeModuleCacheBootstrapCode()}
3795
+ ${command === "build" ? getRuntimeInitResolveBootstrapCode(false, getRuntimeInitStatusImportId(options)) : getRuntimeInitBootstrapCode(false, getRuntimeInitStatusImportId(options), void 0, void 0, exportConditions) + "\n const { initResolve } = globalThis[globalKey];"}
3796
+ ${getRuntimeModuleCacheBootstrapCode(exportConditions)}
3752
3797
  const initTokens = {}
3753
3798
  const shareScopeNames = Array.isArray(${JSON.stringify(options.shareScope)}) ? ${JSON.stringify(options.shareScope)} : [${JSON.stringify(options.shareScope)}]
3754
3799
  const shareScopeName = ${JSON.stringify(hasMultipleShareScopes ? options.shareScope[0] : options.shareScope)}
@@ -4605,13 +4650,14 @@ function getHostAutoInitState(options) {
4605
4650
  }
4606
4651
  return state;
4607
4652
  }
4608
- function generateHostAutoInitCode(remoteEntryImport, _command = "build", options) {
4653
+ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options, exportConditions) {
4609
4654
  const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
4610
4655
  const shouldPreloadShares = resolvedOptions.shareStrategy !== "loaded-first";
4611
4656
  const hostInitShareOrder = JSON.stringify(getOrderedUsedShares(options));
4612
4657
  const cacheOwner = JSON.stringify(resolvedOptions.name);
4658
+ const preferLocalVinextReact = hasPackageDependency("vinext") && (!exportConditions?.includes("browser") || exportConditions.includes("worker"));
4613
4659
  return `
4614
- ${getRuntimeModuleCacheBootstrapCode()}
4660
+ ${getRuntimeModuleCacheBootstrapCode(exportConditions)}
4615
4661
  let hostInitPromise;
4616
4662
  async function initHost() {
4617
4663
  if (!hostInitPromise) {
@@ -4632,21 +4678,34 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
4632
4678
  // a generic full-module key here.
4633
4679
  if (share.treeShaking) continue;
4634
4680
  const cacheDescriptor = __mfGetSharedCacheDescriptor(pkg, share.shareConfig?.singleton, share.version, share.scope);
4635
- if (__mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined) {
4681
+ if (
4682
+ __mfReadSharedCache(__mfModuleCache.share, cacheDescriptor) !== undefined &&
4683
+ __mfReadSharedCacheOwner(__mfModuleCache.share, cacheDescriptor) !== undefined
4684
+ ) {
4636
4685
  continue;
4637
4686
  }
4638
4687
  await runtime.loadShare(pkg, {
4639
4688
  customShareInfo: { shareConfig: share.shareConfig }
4640
- }).then((factory) => {
4689
+ }).then(async (factory) => {
4641
4690
  const mod = typeof factory === "function" ? factory() : factory;
4642
- return Promise.resolve(mod).then((resolved) => {
4643
- __mfWriteSharedCache(
4644
- __mfModuleCache.share,
4645
- cacheDescriptor,
4646
- __mfNormalizeRuntimeShare(resolved),
4647
- ${cacheOwner}
4648
- );
4649
- });
4691
+ let resolved = __mfNormalizeRuntimeShare(await Promise.resolve(mod));
4692
+ ${preferLocalVinextReact ? `if (
4693
+ (pkg === "react" || pkg === "react-dom") &&
4694
+ typeof share.get === "function" &&
4695
+ share.shareConfig?.import !== false
4696
+ ) {
4697
+ try {
4698
+ const localFactory = await share.get();
4699
+ const localModule = typeof localFactory === "function" ? localFactory() : localFactory;
4700
+ resolved = __mfNormalizeRuntimeShare(await Promise.resolve(localModule));
4701
+ } catch {}
4702
+ }` : ""}
4703
+ __mfWriteSharedCache(
4704
+ __mfModuleCache.share,
4705
+ cacheDescriptor,
4706
+ resolved,
4707
+ ${cacheOwner}
4708
+ );
4650
4709
  });
4651
4710
  }
4652
4711
  ` : ""}
@@ -4659,24 +4718,29 @@ function generateHostAutoInitCode(remoteEntryImport, _command = "build", options
4659
4718
  export { initHost, hostInitPromise };
4660
4719
  `;
4661
4720
  }
4662
- function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options) {
4721
+ function writeHostAutoInit(remoteEntryId = REMOTE_ENTRY_ID, command = "build", options, exportConditions) {
4663
4722
  const state = getHostAutoInitState(options);
4664
4723
  state.remoteEntryId = remoteEntryId;
4665
4724
  state.command = command;
4666
- state.module.writeSync(generateHostAutoInitCode(JSON.stringify(remoteEntryId), command, options), true);
4725
+ if (exportConditions !== void 0) state.exportConditions = exportConditions;
4726
+ state.module.writeSync(generateHostAutoInitCode(JSON.stringify(remoteEntryId), command, options, state.exportConditions), true);
4667
4727
  }
4668
- function refreshHostAutoInit(options) {
4728
+ function refreshHostAutoInit(options, exportConditions) {
4669
4729
  try {
4670
4730
  const state = getHostAutoInitState(options);
4671
- writeHostAutoInit(state.remoteEntryId, state.command, options);
4731
+ writeHostAutoInit(state.remoteEntryId, state.command, options, exportConditions);
4672
4732
  } catch {}
4673
4733
  }
4674
4734
  function getHostAutoInitPath(options) {
4675
4735
  return getHostAutoInitState(options).module.getImportId();
4676
4736
  }
4737
+ function isOwnedHostAutoInitId(id, options) {
4738
+ return VirtualModule.findById(id) === getHostAutoInitState(options).module;
4739
+ }
4677
4740
  //#endregion
4678
4741
  //#region src/virtualModules/virtualRemotes.ts
4679
4742
  const cacheRemoteMap = /* @__PURE__ */ new WeakMap();
4743
+ const remoteModuleMetadata = /* @__PURE__ */ new WeakMap();
4680
4744
  const remoteOptionsIds = /* @__PURE__ */ new WeakMap();
4681
4745
  let nextRemoteOptionsId = 1;
4682
4746
  function getRemoteOptionsId(options) {
@@ -4698,10 +4762,24 @@ function getRemoteVirtualModule(remote, command, enableSsrInit = false, consumer
4698
4762
  if (!instanceCache.has(cacheKey)) {
4699
4763
  const virtual = new VirtualModule(`${consumer === "unified" ? remote : `${remote}__mf_consumer__${consumer}`}${MF_OWNER_INFIX}${getRemoteOptionsId(options)}`, LOAD_REMOTE_TAG, ".js", options.internalName);
4700
4764
  virtual.writeSync(generateRemotes(remote, command, enableSsrInit, consumer, options));
4765
+ remoteModuleMetadata.set(virtual, {
4766
+ remote,
4767
+ command,
4768
+ enableSsrInit,
4769
+ consumer,
4770
+ options
4771
+ });
4701
4772
  instanceCache.set(cacheKey, virtual);
4702
4773
  }
4703
4774
  return instanceCache.get(cacheKey);
4704
4775
  }
4776
+ function refreshRemoteModuleForEnvironment(id, options, exportConditions) {
4777
+ const virtual = VirtualModule.findById(id);
4778
+ const metadata = virtual && remoteModuleMetadata.get(virtual);
4779
+ if (!virtual || !metadata || metadata.options !== options) return false;
4780
+ virtual.write(generateRemotes(metadata.remote, metadata.command, metadata.enableSsrInit, metadata.consumer, options, exportConditions));
4781
+ return true;
4782
+ }
4705
4783
  const usedRemotesMap = {};
4706
4784
  const usedRemotesByOptions = /* @__PURE__ */ new WeakMap();
4707
4785
  const dynamicRemotesByOptions = /* @__PURE__ */ new WeakMap();
@@ -4917,7 +4995,7 @@ ${deferRemoteLoad ? getLazyRemotePendingExport() : getEagerRemotePendingExport()
4917
4995
  ${command === "serve" && consumer === "server" ? getServerThenExport() : ""}
4918
4996
  export { __mfDefaultExport as default };`;
4919
4997
  }
4920
- function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options) {
4998
+ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified", options, exportConditions) {
4921
4999
  const resolvedOptions = options ?? getNormalizeModuleFederationOptions();
4922
5000
  const isLoadedFirst = resolvedOptions.shareStrategy === "loaded-first";
4923
5001
  const initMode = resolveRemoteInitMode(resolvedOptions.shareStrategy, consumer);
@@ -4943,9 +5021,9 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
4943
5021
  const browserHostInitCode = `import(${JSON.stringify(hostAutoInitPath)})
4944
5022
  .then((mod) => mod.hostInitPromise)
4945
5023
  .then(initResolve, initReject);`;
4946
- const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath)}
5024
+ const devRuntimeBootstrap = `${getRuntimeInitBootstrapCode(enableSsrInit, getRuntimeInitStatusImportId(options), ssrRemotes, hostAutoInitPath, exportConditions)}
4947
5025
  const { initPromise, initResolve, initReject, moduleCache: __mfModuleCache } = globalThis[globalKey];`;
4948
- const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode()}
5026
+ const importLine = command === "build" ? `${getRuntimeModuleCacheBootstrapCode(exportConditions)}
4949
5027
  import { hostInitPromise as __mfHostInitPromise } from ${JSON.stringify(hostAutoInitPath)};` : `${devRuntimeBootstrap}
4950
5028
  ${command === "serve" && consumer !== "server" ? browserHostInitCode : ""}`;
4951
5029
  const remoteLoadRuntimePromise = command === "build" ? "__mfHostInitPromise" : "initPromise";
@@ -4966,6 +5044,12 @@ function generateRemotes(id, command, enableSsrInit = false, consumer = "unified
4966
5044
  __mfModuleCache.remote[pendingKey] = ${remoteLoadRuntimePromise}
4967
5045
  .then((runtime) => {
4968
5046
  ${registerRemoteCode}
5047
+ const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
5048
+ const shareScopes = runtime.shareScopeMap || {};
5049
+ for (const scope of Object.values(shareScopes)) {
5050
+ if (scope && typeof scope === "object") scope[moduleCacheKey] = __mfModuleCache;
5051
+ }
5052
+ shareScopes[moduleCacheKey] = __mfModuleCache;
4969
5053
  return runtime.loadRemote(${JSON.stringify(runtimeRemoteId)});
4970
5054
  })
4971
5055
  .then((mod) => Promise.resolve(mod?.__mf_remote_dependency_pending).then(() => mod))
@@ -5190,15 +5274,20 @@ const __mfCurrentScript = document.currentScript;
5190
5274
  };
5191
5275
  const __mfRemotePreloads = [${remotePreloads}];
5192
5276
  await Promise.allSettled(__mfRemotePreloads);` : `await initHost();`;
5277
+ const pendingShareLoadsAwait = `
5278
+ if (__mfModuleCache.pendingShareLoads) {
5279
+ await Promise.all(__mfModuleCache.pendingShareLoads);
5280
+ }
5281
+ const __mfReactServerModuleCache = globalThis[${JSON.stringify(getModuleCacheGlobalKey(["react-server"]))}];
5282
+ if (__mfReactServerModuleCache?.pendingShareLoads) {
5283
+ await Promise.all(__mfReactServerModuleCache.pendingShareLoads);
5284
+ }`;
5193
5285
  const importCode = `
5194
5286
  (async () => {
5195
5287
  const __mfHostInit = await ${importExpression(initSrc)};
5196
5288
  await __mfHostInit.__tla;
5197
5289
  const { initHost } = __mfHostInit;
5198
- ${preloadBlock}
5199
- if (__mfModuleCache.pendingShareLoads) {
5200
- await Promise.all(__mfModuleCache.pendingShareLoads);
5201
- }
5290
+ ${preloadBlock}${pendingShareLoadsAwait}
5202
5291
  })().then(() => ${entryImportExpression});
5203
5292
  `;
5204
5293
  return [
@@ -6673,6 +6762,7 @@ function generateRemoteEntrySSR(options) {
6673
6762
  import { init as runtimeInit } from "@module-federation/runtime";
6674
6763
 
6675
6764
  const sharedSingletons = ${JSON.stringify(sharedSingletons)};
6765
+ const moduleCacheKey = Symbol.for(${JSON.stringify(MODULE_CACHE_SHARE_SCOPE_KEY)});
6676
6766
  let exposesMapPromise;
6677
6767
 
6678
6768
  function createShareInitError(errors) {
@@ -6750,7 +6840,8 @@ function generateRemoteEntrySSR(options) {
6750
6840
  throw createShareInitError(shareInitErrors);
6751
6841
  }
6752
6842
  if (cacheEntries.length > 0) {
6753
- const moduleCache = (globalThis.__mf_module_cache__ ||= { share: {}, remote: {} });
6843
+ const moduleCache = shared?.[moduleCacheKey] ||
6844
+ (globalThis.__mf_module_cache__ ||= { share: {}, remote: {} });
6754
6845
  const cache = (moduleCache.share ||= {});
6755
6846
  for (const { scopeName, pkg, module } of cacheEntries) {
6756
6847
  cache[scopeName + ':' + pkg] ??= module;
@@ -7356,6 +7447,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
7356
7447
  const cleanId = id.split("?")[0];
7357
7448
  return cleanId.includes(getHostAutoInitPath(options)) || cleanId.includes(getHostAutoInitPath());
7358
7449
  };
7450
+ const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
7359
7451
  function isRemoteImport(source) {
7360
7452
  return Object.keys(options.remotes).some((name) => source === name || source.startsWith(name + "/"));
7361
7453
  }
@@ -7455,7 +7547,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
7455
7547
  }
7456
7548
  },
7457
7549
  async load(id) {
7458
- if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
7550
+ if (id === remoteEntryId) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
7459
7551
  if (id === virtualExposesId) {
7460
7552
  await refreshExposeRemoteDependencies(this);
7461
7553
  return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
@@ -7465,7 +7557,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
7465
7557
  async transform(code, id) {
7466
7558
  return mapCodeToCodeWithSourcemap(await (async () => {
7467
7559
  if (!filterId(id)) return;
7468
- if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command));
7560
+ if (id.includes(remoteEntryId)) return getParsePromise().then((_) => generateRemoteEntry(options, virtualExposesId, _command, getEnvironmentConditions(this)));
7469
7561
  if (id === virtualExposesId) {
7470
7562
  await refreshExposeRemoteDependencies(this);
7471
7563
  return generateExposes(options, exposeRemoteDependencies, _command, reactIslandExposes);
@@ -7483,7 +7575,7 @@ function pluginProxyRemoteEntry_default({ options, remoteEntryId, virtualExposes
7483
7575
  return `
7484
7576
  const origin = typeof window !== 'undefined' && (${!options.ignoreOrigin}) ? window.origin : ${JSON.stringify(fallbackOrigin)};
7485
7577
  const remoteEntryImport = typeof window !== 'undefined' ? ${isAbsolutePublicPath ? remoteEntryUrl : `origin + ${remoteEntryUrl}`} : ${JSON.stringify(ssrRemoteEntry)};
7486
- ${generateHostAutoInitCode("remoteEntryImport", "serve", options)}
7578
+ ${generateHostAutoInitCode("remoteEntryImport", "serve", options, getEnvironmentConditions(this))}
7487
7579
  `;
7488
7580
  }
7489
7581
  return code;
@@ -7782,6 +7874,8 @@ function proxySharedModule(options) {
7782
7874
  const materializedLoadShareSources = /* @__PURE__ */ new Set();
7783
7875
  const emittedTreeShakingProviders = /* @__PURE__ */ new Set();
7784
7876
  const hasAnalyzableShares = Object.values(shared).some((share) => shouldAnalyzeSharedExports(share));
7877
+ const getEnvironmentConditions = (context) => context.environment?.config?.resolve?.conditions;
7878
+ const refreshTreeShakingForEnvironment = (context) => refreshTreeShakingModules(federationOptions, _command, getIsRolldown(context), getEnvironmentConditions(context));
7785
7879
  const normalizeTreeShakingOutputPath = (value) => {
7786
7880
  const normalized = normalizePathForImport(value);
7787
7881
  if (path$1.posix.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized) || normalized.split("/").includes("..")) throw new Error(`Invalid treeShakingDir "${value}": absolute paths and parent segments are not allowed.`);
@@ -7827,7 +7921,7 @@ function proxySharedModule(options) {
7827
7921
  },
7828
7922
  load(id) {
7829
7923
  if (id === getResolvedLocalSharedImportMapId(federationOptions)) return getParsePromise().then((_) => {
7830
- refreshTreeShakingModules(federationOptions);
7924
+ refreshTreeShakingForEnvironment(this);
7831
7925
  const providerPackages = /* @__PURE__ */ new Set([...Object.keys(shared).filter((pkg) => !pkg.endsWith("/")), ...getUsedShares(federationOptions)]);
7832
7926
  for (const pkg of providerPackages) {
7833
7927
  const sharedKey = findSharedKeyForSource(pkg, shared);
@@ -7879,7 +7973,7 @@ function proxySharedModule(options) {
7879
7973
  if (_command !== "build") return;
7880
7974
  resetTreeShakingExports(federationOptions);
7881
7975
  emittedTreeShakingProviders.clear();
7882
- refreshTreeShakingModules(federationOptions);
7976
+ refreshTreeShakingForEnvironment(this);
7883
7977
  },
7884
7978
  shouldTransformCachedModule() {
7885
7979
  return _command === "build" && hasAnalyzableShares;
@@ -7887,7 +7981,7 @@ function proxySharedModule(options) {
7887
7981
  transform(code, id) {
7888
7982
  if (_command !== "build" || !hasAnalyzableShares) return;
7889
7983
  collectTreeShakingImports(code, id, shared, findSharedKeyForSource, (sharedKey, exports, request) => recordTreeShakingExports(sharedKey, exports, request, federationOptions), (sharedKey, request) => markTreeShakingPackageUnsafe(sharedKey, request, federationOptions));
7890
- refreshTreeShakingModules(federationOptions);
7984
+ refreshTreeShakingForEnvironment(this);
7891
7985
  }
7892
7986
  },
7893
7987
  {
@@ -8826,42 +8920,6 @@ function isTestEnv() {
8826
8920
  return process.env.NODE_ENV === "test" || process.env.VITEST != null || process.env.JEST_WORKER_ID != null;
8827
8921
  }
8828
8922
  //#endregion
8829
- //#region src/utils/sharedExportConditions.ts
8830
- const DEFAULT_CLIENT_EXPORT_CONDITIONS = [
8831
- "browser",
8832
- "import",
8833
- "module",
8834
- "default"
8835
- ];
8836
- const DEFAULT_NODE_SSR_EXPORT_CONDITIONS = [
8837
- "node",
8838
- "import",
8839
- "module",
8840
- "default"
8841
- ];
8842
- const DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS = [
8843
- "worker",
8844
- "browser",
8845
- "import",
8846
- "module",
8847
- "default"
8848
- ];
8849
- const VITE_DEV_PROD_CONDITION = "development|production";
8850
- function appendConditions(conditions, fallbackConditions) {
8851
- return [.../* @__PURE__ */ new Set([...conditions, ...fallbackConditions])];
8852
- }
8853
- function resolveViteModeCondition(conditions, isProduction) {
8854
- const modeCondition = isProduction ? "production" : "development";
8855
- return [...new Set(conditions.map((condition) => condition === VITE_DEV_PROD_CONDITION ? modeCondition : condition))];
8856
- }
8857
- function getSharedExportConditions({ environmentConditions, isProduction, isSsr, rootConditions, ssrConditions, ssrTarget = "node" }) {
8858
- if (environmentConditions !== void 0) return resolveViteModeCondition(appendConditions(environmentConditions, ["import", "default"]), isProduction);
8859
- const defaultConditions = isSsr ? ssrTarget === "webworker" ? DEFAULT_WEBWORKER_SSR_EXPORT_CONDITIONS : DEFAULT_NODE_SSR_EXPORT_CONDITIONS : DEFAULT_CLIENT_EXPORT_CONDITIONS;
8860
- const configuredConditions = isSsr ? ssrConditions ?? rootConditions : rootConditions;
8861
- if (configuredConditions !== void 0) return resolveViteModeCondition(appendConditions(configuredConditions, defaultConditions), isProduction);
8862
- return [...defaultConditions];
8863
- }
8864
- //#endregion
8865
8923
  //#region src/utils/normalizeOptimizeDeps.ts
8866
8924
  var normalizeOptimizeDeps_default = {
8867
8925
  name: "normalizeOptimizeDeps",
@@ -9457,6 +9515,7 @@ function federation(mfUserOptions) {
9457
9515
  ssrTarget
9458
9516
  });
9459
9517
  };
9518
+ const refreshLoadRemoteModuleForEnvironment = (id, context, loadOptions) => refreshRemoteModuleForEnvironment(id, options, getLoadHookExportConditions(context, loadOptions));
9460
9519
  const refreshPreBuildModuleForEnvironment = (id, context, loadOptions) => {
9461
9520
  const pkg = getCachedPreBuildPkg(id);
9462
9521
  if (!pkg) return "not-applicable";
@@ -9520,8 +9579,10 @@ function federation(mfUserOptions) {
9520
9579
  return virtualModule.getResolvedId();
9521
9580
  },
9522
9581
  load(id, loadOptions) {
9582
+ if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
9523
9583
  if (command !== "build" && id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
9524
9584
  if (id.includes("__prebuild__") && refreshPreBuildModuleForEnvironment(id, this, loadOptions) === "not-owned") return;
9585
+ if (id.includes("__H_A_I__") && isOwnedHostAutoInitId(id, options)) refreshHostAutoInit(options, getLoadHookExportConditions(this, loadOptions));
9525
9586
  const virtualModule = VirtualModule.findById(id);
9526
9587
  if (!virtualModule) return;
9527
9588
  if (command === "build" && (id.includes("__loadShare__") || id.includes("__loadRemote__"))) return;
@@ -9742,6 +9803,7 @@ function federation(mfUserOptions) {
9742
9803
  load(id, loadOptions) {
9743
9804
  const loadVirtualModule = (importFalseExportUsage) => {
9744
9805
  if (!id.includes("__loadShare__") && !id.includes("__loadRemote__")) return;
9806
+ if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
9745
9807
  if (id.includes("__loadShare__") && refreshLoadShareModuleForEnvironment(id, this, loadOptions, importFalseExportUsage) === "not-owned") return;
9746
9808
  const virtualModule = VirtualModule.findById(id);
9747
9809
  if (!virtualModule?.code) return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.20.6",
3
+ "version": "1.20.7",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -93,4 +93,4 @@
93
93
  "vite": "8.2.0",
94
94
  "vitest": "4.1.10"
95
95
  }
96
- }
96
+ }