@module-federation/vite 1.20.9 → 1.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -351,20 +351,29 @@ federation({
351
351
  `provideExternalRuntime` injects a local runtime plugin that publishes `runtime-core` on `globalThis._FEDERATION_RUNTIME_CORE`. `externalRuntime` rewrites imports of `@module-federation/runtime-core` to read that global. Using `provideExternalRuntime` together with `exposes` throws — only pure consumers may provide the runtime.
352
352
  The `externalRuntime` rewrite applies to the browser remote graph; SSR remote entries continue to resolve `@module-federation/runtime-core` from Node so they do not depend on the browser global.
353
353
 
354
- ## ⚠️ `codeSplitting` settings are controlled by the plugin
354
+ ## ⚠️ `codeSplitting` is managed by the plugin
355
355
 
356
- Do not set either `build.rollupOptions.output.codeSplitting` or
357
- `build.rolldownOptions.output.codeSplitting` to `false` with this plugin — it will be **automatically ignored**.
356
+ Do not set `build.rollupOptions.output.codeSplitting` or
357
+ `build.rolldownOptions.output.codeSplitting` to `false` — it will be **ignored** (with a warning).
358
+ Module Federation requires chunk splitting so `loadShare` and `runtimeInitStatus` stay isolated for correct bootstrap order.
358
359
 
359
- `codeSplitting.groups` is also ignored because grouping shared-runtime chunks can break MF init order.
360
- Module Federation needs `loadShare` and `runtimeInitStatus` isolated into separate chunks for correct bootstrap behavior.
360
+ ### `codeSplitting.groups` (Vite 8+ / Rolldown)
361
361
 
362
- ## ⚠️ `manualChunks` is not supported
362
+ User groups are now **preserved**. The plugin installs its own federation groups at the highest priority and appends your groups below them, so your groups can only claim modules the federation groups didn't.
363
363
 
364
- Do not use `build.rollupOptions.output.manualChunks` or
365
- `build.rolldownOptions.output.manualChunks` with this plugin it will be **automatically ignored**.
366
- The plugin manages the runtime chunk graph itself, and forcing custom chunk grouping can break Module Federation bootstrap order.
367
- The plugin injects the splits it needs so `runtimeInitStatus` and `loadShare` stay isolated.
364
+ - No warning is emitted just for keeping your groups.
365
+ - If one of your existing groups sets a `priority` high enough to outrank the federation groups, it is **clamped** below them and the plugin warns once. This prevents those groups from capturing a `runtimeInit`/`loadShare` wrapper or the preload helper.
366
+
367
+ ## ⚠️ `manualChunks` behavior depends on your Vite version
368
+
369
+ | Setting | Vite 5–7 (Rollup) | Vite 8+ (Rolldown) |
370
+ | --- | --- | --- |
371
+ | `manualChunks` (function) | **Composed as a fallback** — federation modules are claimed first, everything else falls through to your function | **Ignored** (warns) — move grouping to `codeSplitting.groups` |
372
+ | `manualChunks` (object) | **Ignored** (warns) — use the function form to compose | **Ignored** (warns) — move grouping to `codeSplitting.groups` |
373
+
374
+ On Vite 5–7, Rollup doesn't support `codeSplitting`, so the plugin isolates `runtimeInitStatus`, `loadShare`, and the preload helper via `manualChunks`. A user-provided **function** is called for any module the plugin doesn't claim; the **object** form isn't composed by the plugin and is ignored.
375
+
376
+ On Vite 8+, chunking is managed through `codeSplitting.groups` (see above), so `manualChunks` is removed — express your grouping as `codeSplitting.groups` instead, where user groups are preserved below the federation groups.
368
377
 
369
378
  ### So far so good 🎉
370
379
 
package/lib/index.js CHANGED
@@ -707,9 +707,26 @@ function normalizeShareItem(key, shareItem) {
707
707
  }
708
708
  };
709
709
  }
710
+ /**
711
+ * Trailing-slash keys are package namespace prefixes (`lodash/`, `@scope/ui/`).
712
+ *
713
+ * Packages in COMMON_SHARED_SUBPATHS historically collapsed `pkg/` → `pkg` so
714
+ * Vite would not resolve the invalid `pkg/` specifier, while still auto-mapping
715
+ * known subpaths when a local provider exists.
716
+ *
717
+ * `react/` is different: consumer-only shares need true namespace coverage for
718
+ * any actually-imported subpath, not a hardcoded export list. Keep `react/` as
719
+ * a prefix; concrete subpaths materialize on import via the generic matcher.
720
+ *
721
+ * `react-dom/` must keep collapsing. A browser-wide `react-dom/` prefix would
722
+ * also capture `react-dom/server*`, which is unsafe without environment-aware
723
+ * filtering. Browser-safe entries such as `react-dom/client` stay explicit via
724
+ * COMMON_SHARED_SUBPATHS (local provider) or an exact shared key.
725
+ */
710
726
  function normalizeSharedKey(key) {
711
727
  if (!key.endsWith("/")) return key;
712
728
  const baseKey = key.slice(0, -1);
729
+ if (baseKey === "react") return key;
713
730
  return getCommonSharedSubpaths(baseKey).length > 0 ? baseKey : key;
714
731
  }
715
732
  function normalizeShared(shared) {
@@ -1982,6 +1999,10 @@ function getPackageEsmEntryPath(pkg) {
1982
1999
  }) || resolvePackageEntryFromProjectRoot(pkg);
1983
2000
  }
1984
2001
  const packageNamedExportsCache = /* @__PURE__ */ new Map();
2002
+ const sharedExportInspectionCache = /* @__PURE__ */ new Map();
2003
+ function invalidateSharedExportInspectionCache(filePath) {
2004
+ if (!/(?:^|[/\\])node_modules(?:[/\\]|$)/.test(filePath)) sharedExportInspectionCache.clear();
2005
+ }
1985
2006
  const DEFAULT_SHARED_EXPORT_CONDITIONS = [
1986
2007
  "browser",
1987
2008
  "import",
@@ -2009,17 +2030,22 @@ function hasCommonJsExports(source) {
2009
2030
  return false;
2010
2031
  }
2011
2032
  function inspectSharedExportsFromFile(entryPath, exportConditions = DEFAULT_SHARED_EXPORT_CONDITIONS) {
2033
+ if (!entryPath) return void 0;
2034
+ const cacheKey = `${entryPath}\0${exportConditions.join("\0")}`;
2035
+ if (sharedExportInspectionCache.has(cacheKey)) return sharedExportInspectionCache.get(cacheKey);
2012
2036
  try {
2013
- if (!entryPath) return void 0;
2014
2037
  const source = readFileSync(entryPath, "utf-8");
2015
2038
  const scanState = { complete: true };
2016
2039
  const namedExports = getNamedExportsViaRegex(source, entryPath, void 0, scanState, exportConditions);
2017
2040
  const commonJs = hasCommonJsExports(source);
2018
- return {
2041
+ const inspection = {
2019
2042
  namedExports: scanState.complete && !commonJs ? namedExports : void 0,
2020
2043
  commonJs
2021
2044
  };
2045
+ sharedExportInspectionCache.set(cacheKey, inspection);
2046
+ return inspection;
2022
2047
  } catch {
2048
+ sharedExportInspectionCache.set(cacheKey, void 0);
2023
2049
  return;
2024
2050
  }
2025
2051
  }
@@ -3616,7 +3642,9 @@ const externalSharedProviderSelectionHelperCode = `const __mfSelectExternalShare
3616
3642
  ) => {
3617
3643
  const isLocalProvider = (provider) => __mfMatchesSharedProvider(provider, localShare);
3618
3644
  const candidates = Object.fromEntries(
3619
- Object.entries(versions || {}).filter(([, provider]) => !isLocalProvider(provider))
3645
+ Object.entries(versions || {}).filter(([, provider]) =>
3646
+ !isLocalProvider(provider) && provider?.shareConfig?.import !== false
3647
+ )
3620
3648
  );
3621
3649
  if (localShare?.version && localShare.shareConfig?.import !== false) {
3622
3650
  const sameVersionProvider = candidates[localShare.version];
@@ -4019,6 +4047,7 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
4019
4047
  const needsSharedProviderSelectionHelper = Object.keys(options.shared ?? {}).length > 0;
4020
4048
  const hasTreeShakingShared = Object.values(options.shared ?? {}).some((share) => !!share?.shareConfig.treeShaking);
4021
4049
  const hasMultipleShareScopes = Array.isArray(options.shareScope);
4050
+ const guardHostAutoInit = command === "build" && Object.keys(options.exposes ?? {}).length > 0 && Object.keys(options.remotes ?? {}).length > 0;
4022
4051
  const materializedShareBatches = toSafeJsLiteral(getShareBatches(options, false));
4023
4052
  const runtimeImports = [
4024
4053
  "init as runtimeInit",
@@ -4925,10 +4954,13 @@ function generateRemoteEntry(options, virtualExposesId = getVirtualExposesId(opt
4925
4954
  }
4926
4955
  return (exposesMap[moduleName])().then(res => () => res)
4927
4956
  }
4928
- export {
4929
- init,
4930
- getExposes as get
4957
+ ${guardHostAutoInit ? `let __mfInitPromise;
4958
+ function __mfGuardedInit(shared, initScope) {
4959
+ if (shared === undefined && __mfInitPromise) return __mfInitPromise;
4960
+ __mfInitPromise = init(shared, initScope);
4961
+ return __mfInitPromise;
4931
4962
  }
4963
+ export { __mfGuardedInit as init, getExposes as get }` : `export { init, getExposes as get }`}
4932
4964
  `;
4933
4965
  }
4934
4966
  /**
@@ -5563,6 +5595,7 @@ const addEntry = ({ entryName, entryPath, fileName, inject = "entry", forceClien
5563
5595
  let emittedFileName;
5564
5596
  let skipTransformIds = /* @__PURE__ */ new Set();
5565
5597
  let injectedTransformIds = /* @__PURE__ */ new Set();
5598
+ const ignoredHtmlScriptSources = /* @__PURE__ */ new Set();
5566
5599
  let bootstrapDir = "";
5567
5600
  function skipSvelteKitSsrBuild() {
5568
5601
  return (_command === "build" || viteConfig?.command === "build") && viteConfig?.build?.ssr && hasPackageDependency("@sveltejs/kit");
@@ -5764,6 +5797,10 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
5764
5797
  const scriptRegex = /<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>/gi;
5765
5798
  let match;
5766
5799
  while ((match = scriptRegex.exec(htmlContent)) !== null) {
5800
+ if (/\svite-ignore(?:\s|=|\/?>)/i.test(match[0])) {
5801
+ ignoredHtmlScriptSources.add(match[1]);
5802
+ continue;
5803
+ }
5767
5804
  const scriptSrc = stripQueryAndHash$1(match[1]);
5768
5805
  if (/^(?:[a-z]+:)?\/\//i.test(scriptSrc)) continue;
5769
5806
  addEntryFile(scriptSrc);
@@ -5945,6 +5982,7 @@ for (const __mfRemoteEntryPrefetchUrl of __mfRemoteEntryPrefetchUrls) {
5945
5982
  const scriptRegex = /<script\b(?=[^>]*\btype=["']module["'])(?=[^>]*\bsrc=["']([^"']+)["'])[^>]*>\s*<\/script>/gi;
5946
5983
  let rewritten = false;
5947
5984
  htmlContent = htmlContent.replace(scriptRegex, (scriptTag, entrySrc) => {
5985
+ if (ignoredHtmlScriptSources.has(entrySrc)) return scriptTag;
5948
5986
  rewritten = true;
5949
5987
  const strippedInit = stripBase(initPath);
5950
5988
  const strippedEntry = stripBase(entrySrc);
@@ -9280,8 +9318,11 @@ function getRuntimeCapabilityConfigurationWarnings(options) {
9280
9318
  //#endregion
9281
9319
  //#region src/index.ts
9282
9320
  const patchedManualChunks = /* @__PURE__ */ new WeakSet();
9321
+ const federationGroups = /* @__PURE__ */ new WeakSet();
9283
9322
  const PRELOAD_HELPER_CHUNK = "vite-preload-helper";
9284
9323
  const PRELOAD_HELPER_TEST = /\0?vite\/preload-helper/;
9324
+ const MF_GROUP_PRIORITY = 1e6;
9325
+ const USER_GROUP_MAX_PRIORITY = MF_GROUP_PRIORITY - 1;
9285
9326
  function normalizeVinextRscPreloadHints(code) {
9286
9327
  return code.replace(/(:HL\[[^\]\n]*?,)"stylesheet"/g, "$1\"style\"").replace(/(:HL\[[^\]\n]*?,)\\"stylesheet\\"/g, "$1\\\"style\\\"");
9287
9328
  }
@@ -9771,7 +9812,7 @@ function applyBuildTimeRuntimeDefines(define, options, { target, isAstro, defaul
9771
9812
  }
9772
9813
  function loadPluginDts(options) {
9773
9814
  if (options.dts === false) return [];
9774
- return [import("./pluginDts-BNCg4Gri.js").then(({ default: pluginDts }) => pluginDts(options))];
9815
+ return [import("./pluginDts-sJeW2nss.js").then(({ default: pluginDts }) => pluginDts(options))];
9775
9816
  }
9776
9817
  const INJECT_EXTERNAL_RUNTIME_CORE_PLUGIN = "@module-federation/vite/injectExternalRuntimeCorePlugin";
9777
9818
  function isInjectExternalRuntimeCorePlugin(specifier) {
@@ -9882,6 +9923,11 @@ function federation(mfUserOptions) {
9882
9923
  {
9883
9924
  name: "vite:module-federation-virtual-modules",
9884
9925
  enforce: "pre",
9926
+ configureServer(server) {
9927
+ server.watcher.on("change", invalidateSharedExportInspectionCache);
9928
+ server.watcher.on("add", invalidateSharedExportInspectionCache);
9929
+ server.watcher.on("unlink", invalidateSharedExportInspectionCache);
9930
+ },
9885
9931
  resolveId(id) {
9886
9932
  if (id === "@module-federation/vite/ssrEntryLoader") return resolveImportPath(id);
9887
9933
  let virtualModule = VirtualModule.findById(id);
@@ -10025,33 +10071,33 @@ function federation(mfUserOptions) {
10025
10071
  };
10026
10072
  }
10027
10073
  let warnedAboutCodeSplitting = false;
10028
- let warnedAboutCodeSplittingGroups = false;
10029
10074
  const ensureCodeSplitting = (output) => {
10030
- if (output?.codeSplitting === false) {
10031
- delete output.codeSplitting;
10032
- if (warnedAboutCodeSplitting) return;
10033
- warnedAboutCodeSplitting = true;
10034
- mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
10035
- return;
10075
+ if (output?.codeSplitting !== false) return;
10076
+ delete output.codeSplitting;
10077
+ if (warnedAboutCodeSplitting) return;
10078
+ warnedAboutCodeSplitting = true;
10079
+ mfWarn("Ignoring `output.codeSplitting = false` because module federation requires chunk splitting.");
10080
+ };
10081
+ const isFederationGroup = (group) => typeof group === "object" && group !== null && federationGroups.has(group);
10082
+ let warnedAboutGroupPriority = false;
10083
+ const clampUserGroup = (group) => {
10084
+ const candidate = group;
10085
+ if (typeof candidate?.priority !== "number") return group;
10086
+ if (candidate.priority <= USER_GROUP_MAX_PRIORITY) return group;
10087
+ if (!warnedAboutGroupPriority) {
10088
+ warnedAboutGroupPriority = true;
10089
+ mfWarn(`Clamping \`output.codeSplitting.groups\` priority to ${USER_GROUP_MAX_PRIORITY} — module federation groups must keep the highest priority so shared dependency init wrappers stay isolated in their own chunks.`);
10036
10090
  }
10037
- if (!output?.codeSplitting || typeof output.codeSplitting !== "object") return;
10038
- if (!("groups" in output.codeSplitting)) return;
10039
- const groups = output.codeSplitting.groups;
10040
- if (Array.isArray(groups) && groups.some((group) => typeof group?.name === "function" && patchedManualChunks.has(group.name))) return;
10041
- delete output.codeSplitting.groups;
10042
- if (Object.keys(output.codeSplitting).length === 0) delete output.codeSplitting;
10043
- if (warnedAboutCodeSplittingGroups) return;
10044
- warnedAboutCodeSplittingGroups = true;
10045
- mfWarn("Ignoring `output.codeSplitting.groups` because it conflicts with module federation. Grouping shared dependency init wrappers with their dependent modules can break runtime init order and cause standalone remotes to fail before mount.");
10091
+ return {
10092
+ ...candidate,
10093
+ priority: USER_GROUP_MAX_PRIORITY
10094
+ };
10046
10095
  };
10047
10096
  let warnedAboutManualChunks = false;
10097
+ let warnedAboutObjectManualChunks = false;
10048
10098
  const applyManualChunks = (output, useCodeSplitting) => {
10049
10099
  ensureCodeSplitting(output);
10050
10100
  const isPatchedByPlugin = typeof output.manualChunks === "function" && patchedManualChunks.has(output.manualChunks);
10051
- if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
10052
- warnedAboutManualChunks = true;
10053
- mfWarn("Ignoring `output.manualChunks` because it conflicts with module federation. Module federation transforms shared dependency imports with async init wrappers, and grouping these transformed modules into a single chunk creates circular async dependencies that cause the application to silently hang.");
10054
- }
10055
10101
  const mfChunkName = function(id) {
10056
10102
  if (id.includes(runtimeInitId) || id.includes("__mf_v__runtimeInit__mf_v__")) return "runtimeInit";
10057
10103
  if (id.includes("__loadShare__")) {
@@ -10062,19 +10108,44 @@ function federation(mfUserOptions) {
10062
10108
  };
10063
10109
  patchedManualChunks.add(mfChunkName);
10064
10110
  if (!useCodeSplitting) {
10065
- const mfManualChunks = function(id) {
10111
+ if (isPatchedByPlugin) return;
10112
+ const userManualChunks = output.manualChunks;
10113
+ if (userManualChunks && typeof userManualChunks !== "function" && !warnedAboutObjectManualChunks) {
10114
+ warnedAboutObjectManualChunks = true;
10115
+ mfWarn("Ignoring the object form of `output.manualChunks` because module federation cannot safely compose with it. Use the function form instead: federation modules are claimed first and your function runs for everything else.");
10116
+ }
10117
+ const mfManualChunks = function(id, ...rest) {
10066
10118
  if (PRELOAD_HELPER_TEST.test(id)) return PRELOAD_HELPER_CHUNK;
10067
- return mfChunkName(id) ?? void 0;
10119
+ const mfChunk = mfChunkName(id);
10120
+ if (mfChunk) return mfChunk;
10121
+ if (typeof userManualChunks === "function") return userManualChunks(id, ...rest) ?? void 0;
10068
10122
  };
10069
10123
  patchedManualChunks.add(mfManualChunks);
10070
10124
  output.manualChunks = mfManualChunks;
10071
10125
  return;
10072
10126
  }
10073
- const groups = [{
10127
+ if (output.manualChunks && !isPatchedByPlugin && !warnedAboutManualChunks) {
10128
+ warnedAboutManualChunks = true;
10129
+ mfWarn("Ignoring `output.manualChunks` for the Rolldown build because module federation manages chunking with `output.codeSplitting.groups`. Move your grouping there — user groups are kept below the federation groups.");
10130
+ }
10131
+ const existingGroups = output.codeSplitting && typeof output.codeSplitting === "object" ? output.codeSplitting.groups : void 0;
10132
+ const userGroups = Array.isArray(existingGroups) ? existingGroups.filter((group) => !isFederationGroup(group)).map(clampUserGroup) : [];
10133
+ const mfPreloadGroup = {
10074
10134
  name: PRELOAD_HELPER_CHUNK,
10075
10135
  test: PRELOAD_HELPER_TEST,
10076
- priority: 100
10077
- }, { name: mfChunkName }];
10136
+ priority: 1000001
10137
+ };
10138
+ const mfNameGroup = {
10139
+ name: mfChunkName,
10140
+ priority: MF_GROUP_PRIORITY
10141
+ };
10142
+ federationGroups.add(mfPreloadGroup);
10143
+ federationGroups.add(mfNameGroup);
10144
+ const groups = [
10145
+ mfPreloadGroup,
10146
+ mfNameGroup,
10147
+ ...userGroups
10148
+ ];
10078
10149
  output.codeSplitting = {
10079
10150
  ...output.codeSplitting || {},
10080
10151
  groups
@@ -10127,6 +10198,10 @@ function federation(mfUserOptions) {
10127
10198
  }
10128
10199
  },
10129
10200
  load(id, loadOptions) {
10201
+ if (id.includes("__loadShare__") && id.endsWith("?commonjs-proxy")) {
10202
+ const target = id.slice(id.startsWith("\0") ? 1 : 0, -15);
10203
+ return `export { __moduleExports as default } from ${JSON.stringify(target)};`;
10204
+ }
10130
10205
  const loadVirtualModule = (importFalseExportUsage) => {
10131
10206
  if (!id.includes("__loadShare__") && !id.includes("__loadRemote__")) return;
10132
10207
  if (id.includes("__loadRemote__") && !refreshLoadRemoteModuleForEnvironment(id, this, loadOptions)) return;
@@ -2,6 +2,7 @@ import { n as normalizePathForImport } from "./buildPaths-BkaQHrd2.js";
2
2
  import { _ as mfError, g as createModuleFederationError, l as hasPackageDependency, p as resolveImportPath } from "./dtsConstants-DyJrx8ah.js";
3
3
  import fs from "fs";
4
4
  import * as path$1 from "node:path";
5
+ import os from "os";
5
6
  import { normalizeOptions } from "@module-federation/sdk";
6
7
  import { consumeTypesAPI, generateTypesAPI, isTSProject, normalizeConsumeTypesOptions, normalizeDtsOptions, normalizeGenerateTypesOptions } from "@module-federation/dts-plugin";
7
8
  import { rpc } from "@module-federation/dts-plugin/core";
@@ -12,7 +13,26 @@ const DEFAULT_DEV_OPTIONS = {
12
13
  disableDynamicRemoteTypeHints: false
13
14
  };
14
15
  const DYNAMIC_HINTS_PLUGIN = "@module-federation/dts-plugin/dynamic-remote-type-hints-plugin";
15
- const getIPv4 = () => process.env["FEDERATION_IPV4"] || "127.0.0.1";
16
+ const localIpv4 = "127.0.0.1";
17
+ const getIpv4Interfaces = () => {
18
+ try {
19
+ const interfaces = os.networkInterfaces();
20
+ const ipv4Interfaces = [];
21
+ Object.values(interfaces).forEach((detail) => {
22
+ detail?.forEach((detail) => {
23
+ const familyV4Value = typeof detail.family === "string" ? "IPv4" : 4;
24
+ if (detail.family === familyV4Value && detail.address !== localIpv4) ipv4Interfaces.push(detail);
25
+ });
26
+ });
27
+ return ipv4Interfaces;
28
+ } catch (_err) {
29
+ return [];
30
+ }
31
+ };
32
+ const getIPv4 = () => {
33
+ if (process.env["FEDERATION_IPV4"]) return process.env["FEDERATION_IPV4"];
34
+ return (getIpv4Interfaces()[0] || { address: localIpv4 }).address;
35
+ };
16
36
  const DEV_TYPES_FOLDER = ".dev-server";
17
37
  const forkDevWorkerPath = (() => {
18
38
  return resolveImportPath("@module-federation/dts-plugin/dist/fork-dev-worker.js");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@module-federation/vite",
3
- "version": "1.20.9",
3
+ "version": "1.21.1",
4
4
  "description": "Vite plugin for Module Federation",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",