@lemon-fe/vite-plugin-micro-frontend 2.0.0-beta.1 → 2.0.0-beta.3

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.
@@ -1,5 +1,5 @@
1
1
  import * as _module_federation_bridge_react from '@module-federation/bridge-react';
2
- import { ReactNode, ComponentType } from 'react';
2
+ import { ComponentType } from 'react';
3
3
 
4
4
  interface MicroFrontendLocation {
5
5
  pathname: string;
@@ -7,18 +7,38 @@ interface MicroFrontendLocation {
7
7
  hash: string;
8
8
  state?: unknown;
9
9
  }
10
+ type RouterTo = string | {
11
+ pathname?: string;
12
+ search?: string;
13
+ hash?: string;
14
+ state?: unknown;
15
+ };
16
+ interface MicroFrontendRouterContext {
17
+ location: MicroFrontendLocation;
18
+ history: {
19
+ action?: string;
20
+ length?: number;
21
+ location: MicroFrontendLocation;
22
+ createHref: (to: RouterTo) => string;
23
+ push: (to: RouterTo, state?: unknown) => unknown;
24
+ replace: (to: RouterTo, state?: unknown) => unknown;
25
+ go: (n: number) => unknown;
26
+ goBack: () => unknown;
27
+ goForward: () => unknown;
28
+ listen: (listener: (location: MicroFrontendLocation, action?: string) => void) => () => void;
29
+ block?: (prompt: (location: MicroFrontendLocation, action?: string) => unknown) => () => void;
30
+ };
31
+ match?: unknown;
32
+ staticContext?: unknown;
33
+ }
10
34
  interface MicroFrontendProps {
11
35
  container?: HTMLElement;
12
36
  basename?: string;
13
37
  mountElementId?: string;
14
- /** 基座可选的路由通知。启用 Bridge Router 时由插件自动调用,业务无需透传。 */
15
- onNavigate?: (location: MicroFrontendLocation) => void;
38
+ /** 基座 Router 的 history/location;由 Bridge provider 在微应用 Root 内自动注入 Router。 */
39
+ routerContext?: MicroFrontendRouterContext;
16
40
  [key: string]: unknown;
17
41
  }
18
- /** @internal 为官方 Router 补充基座菜单/页签通知,不接管 history 或 basename。 */
19
- declare function withBridgeRouteSync<Props extends {
20
- children?: ReactNode;
21
- }>(Router: ComponentType<Props>, useLocation: () => MicroFrontendLocation): ComponentType<Props>;
22
42
  interface MicroFrontendLifeCycle {
23
43
  renderContainer: (props: MicroFrontendProps) => void | Promise<void>;
24
44
  bootstrap?: () => void | Promise<void>;
@@ -32,42 +52,14 @@ interface CreateMicroFrontendBridgeProviderOptions {
32
52
  }
33
53
  interface CreateMicroFrontendRootBridgeProviderOptions<Props extends MicroFrontendProps = MicroFrontendProps> {
34
54
  rootComponent: ComponentType<Props>;
55
+ /** 应用在 Bridge 容器内使用的稳定根节点 id。 */
56
+ mountElementId?: string;
35
57
  }
36
- /** 注册完整微应用生命周期;由插件生成的 export-app provider 消费。 */
37
- declare function registerMicroFrontend(lifeCycle: MicroFrontendLifeCycle): void;
38
- /**
39
- * 为现有入口创建官方 React Bridge provider。
40
- * 该函数由构建插件自动注入,业务代码通常不需要直接调用。
41
- */
42
- declare function createMicroFrontendBridgeProvider(options: CreateMicroFrontendBridgeProviderOptions): () => {
43
- render(info: _module_federation_bridge_react.RenderParams): Promise<void>;
44
- destroy(info: _module_federation_bridge_react.DestroyParams): void;
45
- };
46
58
  /** 为组件式应用创建官方 React 18 Bridge provider。 */
47
59
  declare function createMicroFrontendRootBridgeProvider<Props extends MicroFrontendProps = MicroFrontendProps>(options: CreateMicroFrontendRootBridgeProviderOptions<Props>): () => {
48
60
  render(info: _module_federation_bridge_react.RenderParams): Promise<void>;
49
61
  destroy(info: _module_federation_bridge_react.DestroyParams): void;
50
62
  };
51
- /** @deprecated 请改用 MicroFrontendProps。 */
52
- interface QiankunProps extends MicroFrontendProps {
53
- [key: string]: any;
54
- }
55
- /** @deprecated 请改用 MicroFrontendLifeCycle。 */
56
- interface QiankunLifeCycle {
57
- renderContainer: (props: QiankunProps) => void | Promise<void>;
58
- bootstrap?: () => void | Promise<void>;
59
- mount?: (props: QiankunProps) => void | Promise<void>;
60
- unmount?: (props: QiankunProps) => void | Promise<void>;
61
- update?: (props: QiankunProps) => void | Promise<void>;
62
- }
63
- /** @deprecated 请直接使用 Window。 */
64
- interface QiankunWindow extends Window {
65
- [key: string]: any;
66
- }
67
- /** @deprecated 请改用 registerMicroFrontend。名称仅为旧业务入口的源码兼容别名。 */
68
- declare function renderWithQiankun(lifeCycle: QiankunLifeCycle): void;
69
- /** @deprecated 请使用 globalThis/window。该别名不再表示 qiankun proxy window。 */
70
- declare const qiankunWindow: (Window & typeof globalThis) | QiankunWindow;
71
63
 
72
- export { createMicroFrontendBridgeProvider, createMicroFrontendRootBridgeProvider, qiankunWindow, registerMicroFrontend, renderWithQiankun, withBridgeRouteSync };
73
- export type { CreateMicroFrontendBridgeProviderOptions, CreateMicroFrontendRootBridgeProviderOptions, MicroFrontendLifeCycle, MicroFrontendLocation, MicroFrontendProps, QiankunLifeCycle, QiankunProps, QiankunWindow };
64
+ export { createMicroFrontendRootBridgeProvider };
65
+ export type { CreateMicroFrontendBridgeProviderOptions, CreateMicroFrontendRootBridgeProviderOptions, MicroFrontendLifeCycle, MicroFrontendLocation, MicroFrontendProps, MicroFrontendRouterContext };
@@ -1,184 +1,96 @@
1
- import { createContext, createElement, useContext, useRef, useEffect, useState } from 'react';
2
- import ReactDOM from 'react-dom';
1
+ import { createElement, useMemo } from 'react';
3
2
  import { createBridgeComponent } from '@module-federation/bridge-react/v18';
3
+ import { Router, BrowserRouter } from 'react-router-dom';
4
4
 
5
5
  /**
6
6
  * Module Federation React Bridge 运行时。
7
7
  * 这是浏览器入口,不得引入 Node.js API。
8
8
  */
9
- const BridgeNavigationContext = createContext(undefined);
10
- /** @internal 为官方 Router 补充基座菜单/页签通知,不接管 history 或 basename。 */
11
- function withBridgeRouteSync(Router, useLocation) {
12
- function RouteSync() {
13
- const onNavigate = useContext(BridgeNavigationContext);
14
- const location = useLocation();
15
- const lastLocation = useRef();
16
- useEffect(() => {
17
- if (!onNavigate)
18
- return;
19
- const previous = lastLocation.current;
20
- if (previous?.pathname === location.pathname &&
21
- previous.search === location.search &&
22
- previous.hash === location.hash &&
23
- Object.is(previous.state, location.state)) {
24
- return;
25
- }
26
- const next = {
27
- pathname: location.pathname,
28
- search: location.search,
29
- hash: location.hash,
30
- state: location.state,
31
- };
32
- lastLocation.current = next;
33
- onNavigate(next);
34
- }, [location.pathname, location.search, location.hash, location.state, onNavigate]);
35
- return null;
9
+ function stripRouterBasename(pathname, basename) {
10
+ if (!basename || basename === '/')
11
+ return pathname;
12
+ const normalizedBasename = `/${basename.replace(/^\/+|\/+$/g, '')}`;
13
+ if (pathname === normalizedBasename)
14
+ return '/';
15
+ if (pathname.startsWith(`${normalizedBasename}/`)) {
16
+ return pathname.slice(normalizedBasename.length) || '/';
36
17
  }
37
- return function BridgeRouter(props) {
38
- return createElement(Router, props, createElement(RouteSync), props.children);
39
- };
40
- }
41
- const registrations = [];
42
- function findMountElement(container, mountElementId) {
43
- return Array.from(container.querySelectorAll('[id]')).find(element => element.id === mountElementId);
18
+ return pathname;
44
19
  }
45
- function ensureBootstrap(registration) {
46
- if (!registration.bootstrapPromise) {
47
- registration.bootstrapPromise = Promise.resolve(registration.lifeCycle.bootstrap?.());
20
+ function scopeRouterBasename(pathname, basename) {
21
+ // 相对路径交给基座 history 按当前地址解析,提前补 basename 会把它变成绝对路径。
22
+ if (!basename || basename === '/' || (pathname !== '' && !pathname.startsWith('/'))) {
23
+ return pathname;
48
24
  }
49
- return registration.bootstrapPromise;
50
- }
51
- async function mountApplication(registration, props) {
52
- await ensureBootstrap(registration);
53
- if (registration.lifeCycle.mount) {
54
- await registration.lifeCycle.mount(props);
55
- return;
25
+ const normalizedBasename = `/${basename.replace(/^\/+|\/+$/g, '')}`;
26
+ if (pathname === normalizedBasename ||
27
+ pathname.startsWith(`${normalizedBasename}/`) ||
28
+ pathname.startsWith(`${normalizedBasename}?`) ||
29
+ pathname.startsWith(`${normalizedBasename}#`)) {
30
+ return pathname;
56
31
  }
57
- await registration.lifeCycle.renderContainer(props);
32
+ return `${normalizedBasename}${pathname || '/'}`;
58
33
  }
59
- async function unmountApplication(registration, props, mountElementId) {
60
- if (registration.lifeCycle.unmount) {
61
- await registration.lifeCycle.unmount(props);
62
- return;
63
- }
64
- const container = props.container;
65
- const mountElement = container ? findMountElement(container, mountElementId) : undefined;
66
- if (mountElement) {
67
- ReactDOM.unmountComponentAtNode(mountElement);
68
- }
69
- }
70
- /** 注册完整微应用生命周期;由插件生成的 export-app provider 消费。 */
71
- function registerMicroFrontend(lifeCycle) {
72
- const registration = {
73
- lifeCycle,
74
- claimed: false,
75
- standaloneMounted: false,
76
- };
77
- registrations.push(registration);
78
- if (typeof document === 'undefined')
79
- return;
80
- const mountStandalone = () => {
81
- queueMicrotask(() => {
82
- if (registration.claimed || registration.standaloneMounted)
83
- return;
84
- registration.standaloneMounted = true;
85
- void mountApplication(registration, { container: document.body }).catch(error => {
86
- registration.standaloneMounted = false;
87
- console.error('[micro-frontend] 独立运行挂载失败:', error);
88
- });
89
- });
34
+ function adaptRouterContext(context, basename) {
35
+ const { history, location } = context;
36
+ const unscope = (nextLocation) => ({
37
+ ...nextLocation,
38
+ pathname: stripRouterBasename(nextLocation.pathname, basename),
39
+ });
40
+ const toHostLocation = (to) => typeof to === 'string'
41
+ ? scopeRouterBasename(to, basename)
42
+ : typeof to.pathname === 'string'
43
+ ? { ...to, pathname: scopeRouterBasename(to.pathname, basename) }
44
+ : to;
45
+ const scopedLocation = unscope(location);
46
+ const scopedHistory = {
47
+ ...history,
48
+ get action() {
49
+ return history.action;
50
+ },
51
+ get length() {
52
+ return history.length;
53
+ },
54
+ get location() {
55
+ return unscope(history.location);
56
+ },
57
+ createHref: (to) => history.createHref(toHostLocation(to)),
58
+ push: (to, state) => history.push(toHostLocation(to), state),
59
+ replace: (to, state) => history.replace(toHostLocation(to), state),
60
+ listen: (listener) => history.listen((nextLocation, action) => listener(unscope(nextLocation), action)),
61
+ ...(history.block
62
+ ? {
63
+ block: (prompt) => history.block?.((nextLocation, action) => prompt(unscope(nextLocation), action)) ??
64
+ (() => { }),
65
+ }
66
+ : {}),
90
67
  };
91
- if (document.readyState === 'loading') {
92
- document.addEventListener('DOMContentLoaded', mountStandalone, {
93
- once: true,
94
- });
95
- }
96
- else {
97
- mountStandalone();
98
- }
68
+ return { ...context, location: scopedLocation, history: scopedHistory };
99
69
  }
100
- function claimLifeCycle(appName) {
101
- const registration = [...registrations]
102
- .reverse()
103
- .find(candidate => !candidate.claimed && !candidate.standaloneMounted);
104
- if (!registration) {
105
- throw new Error(`[micro-frontend] ${appName} 未注册应用生命周期。` +
106
- '请在 federation.application.entry 中调用 registerMicroFrontend()。');
70
+ function HostRouterProvider(props) {
71
+ const scopedContext = useMemo(() => props.routerContext ? adaptRouterContext(props.routerContext, props.basename) : undefined, [props.basename, props.routerContext]);
72
+ if (scopedContext) {
73
+ return createElement(Router, { history: scopedContext.history }, props.children);
107
74
  }
108
- registration.claimed = true;
109
- return registration;
110
- }
111
- /**
112
- * 为现有入口创建官方 React Bridge provider。
113
- * 该函数由构建插件自动注入,业务代码通常不需要直接调用。
114
- */
115
- function createMicroFrontendBridgeProvider(options) {
116
- const registration = claimLifeCycle(options.appName);
117
- const BridgeApplication = props => {
118
- const containerRef = useRef(null);
119
- const mountPromiseRef = useRef();
120
- const isInitialUpdateEffectRef = useRef(true);
121
- const [mountError, setMountError] = useState();
122
- const mountElementId = props.mountElementId || options.mountElementId;
123
- useEffect(() => {
124
- const container = containerRef.current;
125
- if (!container)
126
- return undefined;
127
- const lifeCycleProps = { ...props, container };
128
- const mountPromise = mountApplication(registration, lifeCycleProps);
129
- mountPromiseRef.current = mountPromise;
130
- mountPromise.catch(setMountError);
131
- return () => {
132
- void mountPromise
133
- .then(() => unmountApplication(registration, lifeCycleProps, mountElementId))
134
- .catch(error => {
135
- console.error('[micro-frontend] 应用卸载失败:', error);
136
- });
137
- };
138
- // Bridge provider 的 dom 生命周期决定挂载和卸载,入口节点 id 不应动态变化。
139
- // eslint-disable-next-line react-hooks/exhaustive-deps
140
- }, []);
141
- useEffect(() => {
142
- if (isInitialUpdateEffectRef.current) {
143
- isInitialUpdateEffectRef.current = false;
144
- return;
145
- }
146
- if (!registration.lifeCycle.update)
147
- return;
148
- void mountPromiseRef.current
149
- ?.then(() => registration.lifeCycle.update?.({
150
- ...props,
151
- container: containerRef.current || undefined,
152
- }))
153
- .catch(setMountError);
154
- }, [props]);
155
- if (mountError) {
156
- throw mountError;
157
- }
158
- return createElement('div', {
159
- ref: containerRef,
160
- 'data-mf-bridge-app': options.appName,
161
- style: { height: '100%', width: '100%' },
162
- }, createElement('div', { id: mountElementId }));
163
- };
164
- return createBridgeComponent({
165
- rootComponent: BridgeApplication,
166
- });
75
+ // SSR/tests have no browser history. The host path is only available when mounted by the base.
76
+ if (typeof window === 'undefined')
77
+ return props.children;
78
+ return createElement(BrowserRouter, undefined, props.children);
167
79
  }
168
80
  /** 为组件式应用创建官方 React 18 Bridge provider。 */
169
81
  function createMicroFrontendRootBridgeProvider(options) {
170
82
  const RootComponent = options.rootComponent;
171
- const BridgeRoot = props => createElement(BridgeNavigationContext.Provider, { value: props.onNavigate }, createElement(RootComponent, props));
83
+ const BridgeRoot = props => {
84
+ const content = createElement(RootComponent, props);
85
+ const routedContent = createElement(HostRouterProvider, { basename: props.basename, routerContext: props.routerContext }, content);
86
+ return options.mountElementId
87
+ ? createElement('div', { id: options.mountElementId }, routedContent)
88
+ : routedContent;
89
+ };
172
90
  return createBridgeComponent({
173
91
  rootComponent: BridgeRoot,
174
92
  });
175
93
  }
176
- /** @deprecated 请改用 registerMicroFrontend。名称仅为旧业务入口的源码兼容别名。 */
177
- function renderWithQiankun(lifeCycle) {
178
- registerMicroFrontend(lifeCycle);
179
- }
180
- /** @deprecated 请使用 globalThis/window。该别名不再表示 qiankun proxy window。 */
181
- const qiankunWindow = typeof window === 'undefined' ? {} : window;
182
94
 
183
- export { createMicroFrontendBridgeProvider, createMicroFrontendRootBridgeProvider, qiankunWindow, registerMicroFrontend, renderWithQiankun, withBridgeRouteSync };
95
+ export { createMicroFrontendRootBridgeProvider };
184
96
  //# sourceMappingURL=runtime-brid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AK,WAAW;QAAE,OAAO,KAAK,CAAC,QAAQ;IACxD,OAAO,aAAa,CAAC,aAAa,EAAE,SAAS,EAAE,KAAK,CAAC,QAAQ,CAAC;AAChE;AAuBA;AACM,SAAU,qCAAqC,CAEnD,OAA4D,EAAA;AAC5D,IAAA,MAAM,aAAa,GAAG,OAAO,CAAC,aAAa;AAC3C,IAAA,MAAM,UAAU,GAAyB,KAAK,IAAG;QAC/C,MAAM,OAAO,GAAG,aAAa,CAAC,aAAa,EAAE,KAAK,CAAC;QAEnD,MAAM,aAAa,GAAG,aAAa,CACjC,kBAAkB,EAClB,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,aAAa,EAAE,KAAK,CAAC,aAAa,EAAE,EAChE,OAAO,CACR;QACD,OAAO,OAAO,CAAC;AACb,cAAE,aAAa,CAAC,KAAK,EAAE,EAAE,EAAE,EAAE,OAAO,CAAC,cAAc,EAAE,EAAE,aAAa;cAClE,aAAa;AACnB,IAAA,CAAC;AAED,IAAA,OAAO,qBAAqB,CAAQ;AAClC,QAAA,aAAa,EAAE,UAAU;AAC1B,KAAA,CAAC;AACJ;;;;"}
@@ -8,10 +8,16 @@ interface DynamicOptions<P = Record<string, unknown>> {
8
8
  /** 加载中/加载失败时显示的组件 */
9
9
  loading?: ComponentType<any>;
10
10
  }
11
+ /**
12
+ * 检测是否是 chunk 加载失败错误
13
+ * 只有这类错误才会被 ErrorBoundary 捕获并显示 Loading
14
+ * 其他业务逻辑错误会继续向上抛出
15
+ */
16
+ declare function isChunkLoadError(error: Error): boolean;
11
17
  /**
12
18
  * 封装动态导入函数,兼容 Umi 的 dynamic
13
19
  */
14
20
  declare function dynamic<P = Record<string, unknown>>(options: DynamicOptions<P>): ComponentType<P>;
15
21
 
16
- export { dynamic };
22
+ export { dynamic, isChunkLoadError };
17
23
  export type { DynamicOptions };
@@ -6,24 +6,8 @@ import { lazy, createElement, Suspense, Component } from 'react';
6
6
  * 其他业务逻辑错误会继续向上抛出
7
7
  */
8
8
  function isChunkLoadError(error) {
9
- const message = error.message || '';
10
- return (
11
- // Vite 动态导入失败
12
- message.includes('Failed to fetch dynamically imported module') ||
13
- // Webpack chunk 加载失败
14
- message.includes('Loading chunk') ||
15
- message.includes('Loading CSS chunk') ||
16
- // 通用的网络/加载错误
17
- error.name === 'ChunkLoadError' ||
18
- // 模块未找到
19
- message.includes('Cannot find module') ||
20
- // 网络错误
21
- message.includes('Failed to fetch') ||
22
- message.includes('NetworkError') ||
23
- // 第三方依赖
24
- message.includes('store') ||
25
- message.includes('dispatch') ||
26
- message.includes('reducer'));
9
+ return (error.name === 'ChunkLoadError' ||
10
+ /Failed to fetch dynamically imported module|Importing a module script failed|error loading dynamically imported module|Loading (?:CSS )?chunk [\s\S]*failed|Unable to preload CSS/i.test(error.message));
27
11
  }
28
12
  /**
29
13
  * Error Boundary - 仅捕获路由/chunk 加载失败的错误
@@ -65,5 +49,5 @@ function dynamic(options) {
65
49
  };
66
50
  }
67
51
 
68
- export { dynamic };
52
+ export { dynamic, isChunkLoadError };
69
53
  //# sourceMappingURL=runtime-dynamic.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-dynamic.js","sources":["../src/runtime/dynamic.ts"],"sourcesContent":[null],"names":[],"mappings":";;AA8BA;;;;AAIG;AACH,SAAS,gBAAgB,CAAC,KAAY,EAAA;AACpC,IAAA,MAAM,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,EAAE;IACnC;;AAEE,IAAA,OAAO,CAAC,QAAQ,CAAC,6CAA6C,CAAC;;AAE/D,QAAA,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAC;AACjC,QAAA,OAAO,CAAC,QAAQ,CAAC,mBAAmB,CAAC;;QAErC,KAAK,CAAC,IAAI,KAAK,gBAAgB;;AAE/B,QAAA,OAAO,CAAC,QAAQ,CAAC,oBAAoB,CAAC;;AAEtC,QAAA,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAC;AACnC,QAAA,OAAO,CAAC,QAAQ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,IAAI,CAAC,KAAK,CAAC,KAAK;QACxB;AACA,QAAA,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ;IAC5B;AACD;AAED;;AAEG;AACG,SAAU,OAAO,CAA8B,OAA0B,EAAA;;IAE7E,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC;AAC1C,IAAA,MAAM,gBAAgB,GAAG,OAAO,CAAC,OAAO;IAExC,OAAO,SAAS,gBAAgB,CAAC,KAAQ,EAAA;AACvC,QAAA,MAAM,cAAc,GAAG,gBAAgB,GAAG,aAAa,CAAC,gBAAgB,CAAC,GAAG,IAAI;QAEhF,OAAO,aAAa,CAClB,oBAAoB,EACpB,EAAE,gBAAgB,EAAE,EACpB,aAAa,CACX,QAAQ,EACR,EAAE,QAAQ,EAAE,cAAc,EAAE,EAC5B,aAAa,CACX,aAAkE,EAClE,KAAgC,CACjC,CACF,CACF;AACH,IAAA,CAAC;AACH;;;;"}
@@ -1,2 +1 @@
1
-
2
- export { };
1
+ export {};
@@ -1,169 +1 @@
1
- const MICRO_FRONTEND_HMR_UPDATE_EVENT = 'micro-frontend:hmr-update';
2
- const SOURCE_EXT_RE = /\.(tsx|ts|jsx|js)$/;
3
- function stripQueryAndHash(value) {
4
- return value.split(/[?#]/)[0];
5
- }
6
- function normalizeMicroFrontendModulePath(value) {
7
- if (!value)
8
- return '';
9
- let normalized = stripQueryAndHash(value.trim());
10
- if (!normalized)
11
- return '';
12
- if (normalized === '*')
13
- return '';
14
- try {
15
- if (/^https?:\/\//.test(normalized)) {
16
- normalized = new URL(normalized).pathname;
17
- }
18
- }
19
- catch {
20
- // Keep the original value if URL parsing fails.
21
- }
22
- if (normalized.startsWith('@/')) {
23
- normalized = `/src/${normalized.slice(2)}`;
24
- }
25
- const srcIndex = normalized.indexOf('/src/');
26
- if (srcIndex >= 0) {
27
- normalized = normalized.slice(srcIndex);
28
- }
29
- normalized = normalized.replace(/\\/g, '/');
30
- if (!normalized.startsWith('/')) {
31
- normalized = `/${normalized}`;
32
- }
33
- return normalized.replace(SOURCE_EXT_RE, '');
34
- }
35
- function collectMicroFrontendHmrPaths(payload) {
36
- const paths = new Set();
37
- const data = payload;
38
- if (data?.path)
39
- paths.add(data.path);
40
- if (data?.triggeredBy)
41
- paths.add(data.triggeredBy);
42
- data?.paths?.forEach(path => paths.add(path));
43
- data?.updates?.forEach(update => {
44
- if (update.path)
45
- paths.add(update.path);
46
- if (update.acceptedPath)
47
- paths.add(update.acceptedPath);
48
- });
49
- return Array.from(paths)
50
- .map(path => normalizeMicroFrontendModulePath(path))
51
- .filter(Boolean);
52
- }
53
- function getPathVersionStore(target) {
54
- const win = target;
55
- if (!win.__MICRO_FRONTEND_HMR_PATH_VERSIONS__) {
56
- win.__MICRO_FRONTEND_HMR_PATH_VERSIONS__ = {};
57
- }
58
- return win.__MICRO_FRONTEND_HMR_PATH_VERSIONS__;
59
- }
60
- function recordMicroFrontendHmrUpdate(detail) {
61
- const version = detail.version ?? detail.timestamp ?? Date.now();
62
- const paths = [...(detail.paths ?? []), ...(detail.invalidationPaths ?? [])]
63
- .map(path => normalizeMicroFrontendModulePath(path))
64
- .filter(Boolean);
65
- if (paths.length === 0)
66
- return;
67
- getWindowTargets().forEach(target => {
68
- const store = getPathVersionStore(target);
69
- paths.forEach(path => {
70
- store[path] = Math.max(store[path] ?? 0, version);
71
- });
72
- });
73
- }
74
- function getWindowTargets() {
75
- if (typeof window === 'undefined')
76
- return [];
77
- return [window];
78
- }
79
- function emitMicroFrontendHmrUpdate(detail) {
80
- const timestamp = detail.timestamp ?? Date.now();
81
- const eventDetail = {
82
- ...detail,
83
- paths: detail.paths?.map(path => normalizeMicroFrontendModulePath(path)).filter(Boolean),
84
- invalidationPaths: detail.invalidationPaths
85
- ?.map(path => normalizeMicroFrontendModulePath(path))
86
- .filter(Boolean),
87
- version: detail.version ?? timestamp,
88
- timestamp,
89
- };
90
- recordMicroFrontendHmrUpdate(eventDetail);
91
- getWindowTargets().forEach(target => {
92
- target.dispatchEvent(new CustomEvent(MICRO_FRONTEND_HMR_UPDATE_EVENT, { detail: eventDetail }));
93
- });
94
- }
95
-
96
- /// <reference types="vite/client" />
97
- /// <reference path="./react-refresh-init.d.ts" />
98
- function hasReactRefreshRenderer(target) {
99
- const renderers = target.__REACT_DEVTOOLS_GLOBAL_HOOK__
100
- ?.renderers;
101
- if (!renderers)
102
- return false;
103
- return Array.from(renderers.values()).some(renderer => typeof renderer.scheduleRefresh === 'function');
104
- }
105
- const isDev = import.meta.env?.DEV ?? false;
106
- if (isDev) {
107
- const win = window;
108
- const reloadEventName = 'micro-frontend:reload';
109
- /** 在当前 window 上设置 preamble,供 @vitejs/plugin-react 使用。 */
110
- const setPreamble = (target) => {
111
- if (!target.$RefreshReg$)
112
- target.$RefreshReg$ = () => { };
113
- if (!target.$RefreshSig$)
114
- target.$RefreshSig$ = () => (type) => type;
115
- target.__vite_plugin_react_preamble_installed__ = true;
116
- };
117
- setPreamble(win);
118
- const handleReloadEvent = (event) => {
119
- const detail = event.detail;
120
- const paths = collectMicroFrontendHmrPaths(detail);
121
- if (paths.length > 0) {
122
- emitMicroFrontendHmrUpdate({
123
- source: detail?.source ?? 'reload-event',
124
- type: detail?.type,
125
- paths,
126
- timestamp: detail?.timestamp,
127
- });
128
- return;
129
- }
130
- console.warn('[micro-frontend] Skip reload request without matched module paths.');
131
- };
132
- win.addEventListener(reloadEventName, handleReloadEvent);
133
- if (import.meta.hot) {
134
- import.meta.hot.on('vite:afterUpdate', (detail) => {
135
- const paths = collectMicroFrontendHmrPaths(detail);
136
- if (paths.length === 0)
137
- return;
138
- // 生产基座通常提供 production ReactDOM singleton,它没有 Fast Refresh renderer。
139
- // 保持 React 单例一致性,并在这种场景下降级为自动整页刷新以应用本地更新。
140
- if (!hasReactRefreshRenderer(win)) {
141
- win.location.reload();
142
- return;
143
- }
144
- emitMicroFrontendHmrUpdate({
145
- source: 'vite-after-update',
146
- type: detail?.type ?? 'update',
147
- paths,
148
- timestamp: Date.now(),
149
- });
150
- });
151
- import.meta.hot.on(reloadEventName, (detail) => {
152
- const paths = collectMicroFrontendHmrPaths(detail);
153
- if (paths.length > 0) {
154
- emitMicroFrontendHmrUpdate({
155
- source: detail?.source ?? 'vite-custom',
156
- type: detail?.type,
157
- paths,
158
- timestamp: detail?.timestamp,
159
- });
160
- return;
161
- }
162
- console.warn('[micro-frontend] Skip reload request without matched module paths.');
163
- });
164
- import.meta.hot.on('vite:error', (err) => {
165
- console.error('[React Refresh] HMR error:', err);
166
- });
167
- }
168
- }
169
- //# sourceMappingURL=runtime-react-refresh-init.js.map
1
+ export {};