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

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.
@@ -0,0 +1,37 @@
1
+ import * as react from 'react';
2
+ import { ReactNode, ComponentType } from 'react';
3
+ import { useHistory } from 'react-router-dom';
4
+
5
+ type AppHistory = ReturnType<typeof useHistory>;
6
+ /** 普通组件微应用接收的宿主能力。 */
7
+ interface MicroFrontendProps {
8
+ /** 应用路由前缀,例如 /wms。 */
9
+ basename?: string;
10
+ /** 向基座登记当前应用的错误监控信息。 */
11
+ setSentryMetadata?: (metadata: {
12
+ dsn: string;
13
+ release: string;
14
+ }) => void;
15
+ }
16
+ /** 复用宿主 history,仅转换应用绝对路径的前缀,不创建浏览器 history。 */
17
+ declare function createScopedHistory(originHistory: AppHistory, basename: string): AppHistory;
18
+ interface AppRouterProps {
19
+ /** 应用路由前缀。 */
20
+ basename: string;
21
+ /** 应用组件树。 */
22
+ children?: ReactNode;
23
+ }
24
+ declare function AppRouter({ basename, children }: AppRouterProps): react.CElement<{
25
+ history: any;
26
+ }, react.Component<{
27
+ history: any;
28
+ }, any, any>>;
29
+ /** 为插件生成的 ./app 提供普通 React 组件与应用路由前缀。 */
30
+ declare function createMicroFrontendApp<Props extends MicroFrontendProps = MicroFrontendProps>(options: {
31
+ rootComponent: ComponentType<Props>;
32
+ basename: string;
33
+ mountElementId?: string;
34
+ }): ComponentType<Props>;
35
+
36
+ export { AppRouter, createMicroFrontendApp, createScopedHistory };
37
+ export type { AppRouterProps, MicroFrontendProps };
@@ -0,0 +1,82 @@
1
+ import { useMemo, createElement } from 'react';
2
+ import { useHistory, Router } from 'react-router-dom';
3
+
4
+ function hasBasename(pathname, basename) {
5
+ const path = pathname.split(/[?#]/)[0];
6
+ return basename === '' || path === basename || path.startsWith(`${basename}/`);
7
+ }
8
+ function addBasename(location, basename) {
9
+ if (!basename)
10
+ return location;
11
+ if (typeof location === 'string') {
12
+ // 相对路径、query 和 hash 交给宿主 history 按当前地址解析。
13
+ if (location !== '' && !location.startsWith('/'))
14
+ return location;
15
+ return hasBasename(location, basename) ? location : `${basename}${location || '/'}`;
16
+ }
17
+ if (location.pathname === undefined ||
18
+ (location.pathname !== '' && !location.pathname.startsWith('/')) ||
19
+ hasBasename(location.pathname, basename)) {
20
+ return location;
21
+ }
22
+ return { ...location, pathname: `${basename}${location.pathname || '/'}` };
23
+ }
24
+ function removeBasename(location, basename) {
25
+ if (!basename || !hasBasename(location.pathname, basename))
26
+ return location;
27
+ return { ...location, pathname: location.pathname.slice(basename.length) || '/' };
28
+ }
29
+ /** 复用宿主 history,仅转换应用绝对路径的前缀,不创建浏览器 history。 */
30
+ function createScopedHistory(originHistory, basename) {
31
+ const prefix = !basename || basename === '/' ? '' : `/${basename.replace(/^\/+|\/+$/g, '')}`;
32
+ return {
33
+ get length() {
34
+ return originHistory.length;
35
+ },
36
+ get action() {
37
+ return originHistory.action;
38
+ },
39
+ get location() {
40
+ return removeBasename(originHistory.location, prefix);
41
+ },
42
+ createHref(location) {
43
+ return originHistory.createHref(addBasename(location, prefix));
44
+ },
45
+ push(location, state) {
46
+ originHistory.push(addBasename(location, prefix), state);
47
+ },
48
+ replace(location, state) {
49
+ originHistory.replace(addBasename(location, prefix), state);
50
+ },
51
+ go: originHistory.go,
52
+ goBack: originHistory.goBack,
53
+ goForward: originHistory.goForward,
54
+ listen(listener) {
55
+ return originHistory.listen((location, action) => {
56
+ listener(removeBasename(location, prefix), action);
57
+ });
58
+ },
59
+ block(prompt) {
60
+ if (typeof prompt !== 'function')
61
+ return originHistory.block(prompt);
62
+ return originHistory.block((location, action) => prompt(removeBasename(location, prefix), action));
63
+ },
64
+ };
65
+ }
66
+ function AppRouter({ basename, children }) {
67
+ const history = useHistory();
68
+ const scopedHistory = useMemo(() => createScopedHistory(history, basename), [history, basename]);
69
+ return createElement(Router, { history: scopedHistory }, children);
70
+ }
71
+ /** 为插件生成的 ./app 提供普通 React 组件与应用路由前缀。 */
72
+ function createMicroFrontendApp(options) {
73
+ return function MicroFrontendApp(props) {
74
+ const content = createElement(options.rootComponent, props);
75
+ return createElement(AppRouter, { basename: props.basename ?? options.basename }, options.mountElementId
76
+ ? createElement('div', { id: options.mountElementId, style: { width: '100%', height: '100%' } }, content)
77
+ : content);
78
+ };
79
+ }
80
+
81
+ export { AppRouter, createMicroFrontendApp, createScopedHistory };
82
+ //# sourceMappingURL=runtime-app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-app.js","sources":["../src/runtime/app.ts"],"sourcesContent":[null],"names":[],"mappings":";;;AAeA,SAAS,WAAW,CAAC,QAAgB,EAAE,QAAgB,EAAA;IACrD,MAAM,IAAI,GAAG,QAAQ,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;AACtC,IAAA,OAAO,QAAQ,KAAK,EAAE,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,CAAA,EAAG,QAAQ,CAAA,CAAA,CAAG,CAAC;AAChF;AAOA,SAAS,WAAW,CAAC,QAA+B,EAAE,QAAgB,EAAA;AACpE,IAAA,IAAI,CAAC,QAAQ;AAAE,QAAA,OAAO,QAAQ;AAC9B,IAAA,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE;;QAEhC,IAAI,QAAQ,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC;AAAE,YAAA,OAAO,QAAQ;QACjE,OAAO,WAAW,CAAC,QAAQ,EAAE,QAAQ,CAAC,GAAG,QAAQ,GAAG,GAAG,QAAQ,CAAA,EAAG,QAAQ,IAAI,GAAG,EAAE;IACrF;AACA,IAAA,IACE,QAAQ,CAAC,QAAQ,KAAK,SAAS;AAC/B,SAAC,QAAQ,CAAC,QAAQ,KAAK,EAAE,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;QAChE,WA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AC3C,MAAM,OAAO,GAAG,aAAa,CAAC,OAAO,CAAC,aAAa,EAAE,KAAK,CAAC;AAC3D,QAAA,OAAO,aAAa,CAClB,SAAS,EACT,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,IAAI,OAAO,CAAC,QAAQ,EAAE,EAChD,OAAO,CAAC;cACJ,aAAa,CACX,KAAK,EACL,EAAE,EAAE,EAAE,OAAO,CAAC,cAAc,EAAE,KAAK,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,EAAE,EACxE,OAAO;cAET,OAAO,CACZ;AACH,IAAA,CAAC;AACH;;;;"}
@@ -1,11 +1,5 @@
1
- import * as react from 'react';
2
1
  import { ComponentType } from 'react';
3
2
 
4
- type ResourceLoadRecovery = (error: Error, options?: {
5
- manual?: boolean;
6
- }) => Promise<boolean>;
7
- /** 由 Bridge provider 按应用注入,不通过 window 共享多个微应用的恢复状态。 */
8
- declare const ResourceLoadRecoveryContext: react.Context<ResourceLoadRecovery | undefined>;
9
3
  interface DynamicOptions<P = Record<string, unknown>> {
10
4
  /** 动态加载函数,返回一个包含 default 导出的 Promise */
11
5
  loader: () => Promise<{
@@ -25,5 +19,5 @@ declare function isChunkLoadError(error: Error): boolean;
25
19
  */
26
20
  declare function dynamic<P = Record<string, unknown>>(options: DynamicOptions<P>): ComponentType<P>;
27
21
 
28
- export { ResourceLoadRecoveryContext, dynamic, isChunkLoadError };
29
- export type { DynamicOptions, ResourceLoadRecovery };
22
+ export { dynamic, isChunkLoadError };
23
+ export type { DynamicOptions };
@@ -1,7 +1,5 @@
1
- import { createContext, Component, createElement, lazy, Suspense } from 'react';
1
+ import { lazy, createElement, Suspense, Component } from 'react';
2
2
 
3
- /** 由 Bridge provider 按应用注入,不通过 window 共享多个微应用的恢复状态。 */
4
- const ResourceLoadRecoveryContext = createContext(undefined);
5
3
  /**
6
4
  * 检测是否是 chunk 加载失败错误
7
5
  * 只有这类错误才会被 ErrorBoundary 捕获并显示 Loading
@@ -18,49 +16,19 @@ function isChunkLoadError(error) {
18
16
  class DynamicErrorBoundary extends Component {
19
17
  constructor(props) {
20
18
  super(props);
21
- this.disposed = false;
22
- this.state = { hasError: false, error: null, recovering: false, recoveryAttempted: false };
19
+ this.state = { hasError: false, error: null };
23
20
  }
24
21
  static getDerivedStateFromError(error) {
25
22
  // 先捕获所有错误,在 render 中根据错误类型决定处理方式
26
23
  return { hasError: true, error };
27
24
  }
28
- componentDidMount() {
29
- this.disposed = false;
30
- }
31
- componentWillUnmount() {
32
- this.disposed = true;
33
- }
34
- componentDidCatch(error) {
35
- if (isChunkLoadError(error) && this.context)
36
- this.recover(error);
37
- }
38
- recover(error, manual = false) {
39
- const handler = this.context;
40
- if (!handler || this.state.recovering)
41
- return;
42
- this.setState({ recovering: true, recoveryAttempted: true });
43
- void Promise.resolve()
44
- .then(() => handler(error, { manual }))
45
- .catch(() => false)
46
- .then(reloading => {
47
- if (!this.disposed && !reloading)
48
- this.setState({ recovering: false });
49
- });
50
- }
51
25
  render() {
52
26
  if (this.state.hasError && this.state.error) {
53
27
  // 只有 chunk 加载错误才显示 Loading 组件
54
- if (isChunkLoadError(this.state.error)) {
55
- const recovering = this.state.recovering || (this.context && !this.state.recoveryAttempted);
56
- if (this.props.LoadingComponent) {
57
- return createElement(this.props.LoadingComponent, {
58
- error: recovering ? undefined : this.state.error,
59
- retry: this.context ? () => this.recover(this.state.error, true) : undefined,
60
- });
61
- }
62
- if (recovering)
63
- return null;
28
+ if (isChunkLoadError(this.state.error) && this.props.LoadingComponent) {
29
+ return createElement(this.props.LoadingComponent, {
30
+ error: this.state.error,
31
+ });
64
32
  }
65
33
  // 业务逻辑错误:重新抛出,让上层处理
66
34
  throw this.state.error;
@@ -68,7 +36,6 @@ class DynamicErrorBoundary extends Component {
68
36
  return this.props.children;
69
37
  }
70
38
  }
71
- DynamicErrorBoundary.contextType = ResourceLoadRecoveryContext;
72
39
  /**
73
40
  * 封装动态导入函数,兼容 Umi 的 dynamic
74
41
  */
@@ -82,5 +49,5 @@ function dynamic(options) {
82
49
  };
83
50
  }
84
51
 
85
- export { ResourceLoadRecoveryContext, dynamic, isChunkLoadError };
52
+ export { dynamic, isChunkLoadError };
86
53
  //# sourceMappingURL=runtime-dynamic.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime-dynamic.js","sources":["../src/runtime/dynamic.ts"],"sourcesContent":[null],"names":[],"mappings":";;AAgBA;MACa,2BAA2B,GAAG,aAAa,CACtD,SAAS;AA0BX;;;;AAIG;AACG,SAAU,gBAAgB,CAAC,KAAY,EAAA;AAC3C,IAAA,QACE,KAAK,CAAC,IAAI,KAAK,gBAAgB;QAC/B,oLAAoL,CAAC,IAAI,CACvL,KAAK,CAAC,OAAO,CACd;AAEL;AAEA;;;AAGG;AACH,MAAM,oBAAqB,SAAQ,SAAiD,CAAA;AAKlF,IAAA,WAAA,CAAY,KAAyB,EAAA;QACnC,KAAK,CAAC,KAAK,CAAC;QAHN,IAAA,CAAA,QAAQ,GAAG,KAAK;QAItB,IAAI,CAAC,KAAK,GAAG,EAAE,QAAQ,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,KAAK,EAAE,iBAAiB,EAAE,KAAK,EAAE;IAC5F;IAEA,OAAO,wBAAwB,CAAC,KAAY,EAAA;;AAE1C,QAAA,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,KAAK,EAAE;IAClC;IAEA,iBAAiB,GAAA;AACf,QAAA,IAAI,CAAC,QAAQ,GAAG,KAAK;IACvB;IAEA,oBAAoB,GAAA;AAClB,QAAA,IAAI,CAAC,QAAQ,GAAG,IAAI;IACtB;AAEA,IAAA,iBAAiB,CAAC,KAAY,EAAA;AAC5B,QAAA,IAAI,gBAAgB,CAAC,KAAK,CAAC,IAAI,IAAI,CAAC,OAAO;AAAE,YAAA,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC;IAClE;AAEQ,IAAA,OAAO,CAAC,KAAY,EAAE,MAA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QueryAndHash(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 {};
package/dist/runtime.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- /** @deprecated 请优先使用 runtime/dynamic 或 runtime/bridge 子路径 */
2
- export * from './runtime-bridge';
1
+ /** @deprecated 请优先使用 runtime/dynamic 或 runtime/app 子路径 */
2
+ export * from './runtime-app';
3
3
  export * from './runtime-dynamic';
package/dist/runtime.js CHANGED
@@ -1,3 +1,3 @@
1
- /** @deprecated 请优先使用 runtime/dynamic 或 runtime/bridge 子路径 */
2
- export * from './runtime-bridge.js';
1
+ /** @deprecated 请优先使用 runtime/dynamic 或 runtime/app 子路径 */
2
+ export * from './runtime-app.js';
3
3
  export * from './runtime-dynamic.js';
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@lemon-fe/vite-plugin-micro-frontend",
3
- "version": "2.0.0-beta.2",
4
- "description": "基于 Module Federation Runtime 与 React Bridge 的 Vite 微前端插件集合",
3
+ "version": "2.0.0",
4
+ "description": "基于 Module Federation Runtime 与 React 组件的 Vite 微前端插件集合",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
7
7
  "types": "./dist/index.d.ts",
@@ -21,9 +21,9 @@
21
21
  "types": "./dist/runtime-dynamic.d.ts",
22
22
  "default": "./dist/runtime-dynamic.js"
23
23
  },
24
- "./runtime/bridge": {
25
- "types": "./dist/runtime-bridge.d.ts",
26
- "default": "./dist/runtime-bridge.js"
24
+ "./runtime/app": {
25
+ "types": "./dist/runtime-app.d.ts",
26
+ "default": "./dist/runtime-app.js"
27
27
  },
28
28
  "./runtime/federation": {
29
29
  "types": "./dist/runtime-federation.d.ts",
@@ -42,8 +42,8 @@
42
42
  "runtime/dynamic": [
43
43
  "./dist/runtime-dynamic.d.ts"
44
44
  ],
45
- "runtime/bridge": [
46
- "./dist/runtime-bridge.d.ts"
45
+ "runtime/app": [
46
+ "./dist/runtime-app.d.ts"
47
47
  ],
48
48
  "runtime/federation": [
49
49
  "./dist/runtime-federation.d.ts"
@@ -57,7 +57,6 @@
57
57
  "scripts": {
58
58
  "build": "rollup -c",
59
59
  "dev": "rollup -c -w",
60
- "prepare": "npm run build",
61
60
  "prepublishOnly": "npm run build"
62
61
  },
63
62
  "keywords": [
@@ -65,7 +64,7 @@
65
64
  "vite-plugin",
66
65
  "micro-frontend",
67
66
  "module-federation",
68
- "react-bridge",
67
+ "react",
69
68
  "routes"
70
69
  ],
71
70
  "author": "",
@@ -76,13 +75,13 @@
76
75
  "peerDependencies": {
77
76
  "react": "^18.0.0",
78
77
  "react-dom": "^18.0.0",
78
+ "react-router": "^5.0.0",
79
+ "react-router-dom": "^5.0.0",
79
80
  "vite": "^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
80
81
  },
81
82
  "dependencies": {
82
- "@module-federation/bridge-react": "2.9.0",
83
83
  "@module-federation/runtime": "2.9.0",
84
84
  "@module-federation/vite": "1.21.4",
85
- "chokidar": "^4.0.3",
86
85
  "prettier": "^3.5.3",
87
86
  "vite-plugin-dynamic-base": "^1.3.0"
88
87
  },
@@ -99,6 +98,7 @@
99
98
  "@types/node": "^22.0.0",
100
99
  "@types/react": "^18.0.0",
101
100
  "@types/react-dom": "^18.0.0",
101
+ "chokidar": "^4.0.3",
102
102
  "rollup": "^4.21.2",
103
103
  "rollup-plugin-dts": "^6.1.1",
104
104
  "tslib": "^2.8.0",
@@ -1,76 +0,0 @@
1
- import * as _module_federation_bridge_react from '@module-federation/bridge-react';
2
- import { ReactNode, ComponentType } from 'react';
3
- import { ResourceLoadRecovery } from './runtime-dynamic.js';
4
-
5
- interface MicroFrontendLocation {
6
- pathname: string;
7
- search: string;
8
- hash: string;
9
- state?: unknown;
10
- }
11
- interface MicroFrontendProps {
12
- container?: HTMLElement;
13
- basename?: string;
14
- mountElementId?: string;
15
- /** 基座可选的路由通知。启用 Bridge Router 时由插件自动调用,业务无需透传。 */
16
- onNavigate?: (location: MicroFrontendLocation) => void;
17
- /** 资源加载失败时请求基座检查版本并局部重载当前应用。 */
18
- onResourceLoadError?: ResourceLoadRecovery;
19
- [key: string]: unknown;
20
- }
21
- /** @internal 为官方 Router 补充基座菜单/页签通知,不接管 history 或 basename。 */
22
- declare function withBridgeRouteSync<Props extends {
23
- children?: ReactNode;
24
- }>(Router: ComponentType<Props>, useLocation: () => MicroFrontendLocation): ComponentType<Props>;
25
- interface MicroFrontendLifeCycle {
26
- renderContainer: (props: MicroFrontendProps) => void | Promise<void>;
27
- bootstrap?: () => void | Promise<void>;
28
- mount?: (props: MicroFrontendProps) => void | Promise<void>;
29
- unmount?: (props: MicroFrontendProps) => void | Promise<void>;
30
- update?: (props: MicroFrontendProps) => void | Promise<void>;
31
- }
32
- interface CreateMicroFrontendBridgeProviderOptions {
33
- appName: string;
34
- mountElementId: string;
35
- }
36
- interface CreateMicroFrontendRootBridgeProviderOptions<Props extends MicroFrontendProps = MicroFrontendProps> {
37
- rootComponent: ComponentType<Props>;
38
- }
39
- /** 注册完整微应用生命周期;由插件生成的 export-app provider 消费。 */
40
- declare function registerMicroFrontend(lifeCycle: MicroFrontendLifeCycle): void;
41
- /**
42
- * 为现有入口创建官方 React Bridge provider。
43
- * 该函数由构建插件自动注入,业务代码通常不需要直接调用。
44
- */
45
- declare function createMicroFrontendBridgeProvider(options: CreateMicroFrontendBridgeProviderOptions): () => {
46
- render(info: _module_federation_bridge_react.RenderParams): Promise<void>;
47
- destroy(info: _module_federation_bridge_react.DestroyParams): void;
48
- };
49
- /** 为组件式应用创建官方 React 18 Bridge provider。 */
50
- declare function createMicroFrontendRootBridgeProvider<Props extends MicroFrontendProps = MicroFrontendProps>(options: CreateMicroFrontendRootBridgeProviderOptions<Props>): () => {
51
- render(info: _module_federation_bridge_react.RenderParams): Promise<void>;
52
- destroy(info: _module_federation_bridge_react.DestroyParams): void;
53
- };
54
- /** @deprecated 请改用 MicroFrontendProps。 */
55
- interface QiankunProps extends MicroFrontendProps {
56
- [key: string]: any;
57
- }
58
- /** @deprecated 请改用 MicroFrontendLifeCycle。 */
59
- interface QiankunLifeCycle {
60
- renderContainer: (props: QiankunProps) => void | Promise<void>;
61
- bootstrap?: () => void | Promise<void>;
62
- mount?: (props: QiankunProps) => void | Promise<void>;
63
- unmount?: (props: QiankunProps) => void | Promise<void>;
64
- update?: (props: QiankunProps) => void | Promise<void>;
65
- }
66
- /** @deprecated 请直接使用 Window。 */
67
- interface QiankunWindow extends Window {
68
- [key: string]: any;
69
- }
70
- /** @deprecated 请改用 registerMicroFrontend。名称仅为旧业务入口的源码兼容别名。 */
71
- declare function renderWithQiankun(lifeCycle: QiankunLifeCycle): void;
72
- /** @deprecated 请使用 globalThis/window。该别名不再表示 qiankun proxy window。 */
73
- declare const qiankunWindow: (Window & typeof globalThis) | QiankunWindow;
74
-
75
- export { createMicroFrontendBridgeProvider, createMicroFrontendRootBridgeProvider, qiankunWindow, registerMicroFrontend, renderWithQiankun, withBridgeRouteSync };
76
- export type { CreateMicroFrontendBridgeProviderOptions, CreateMicroFrontendRootBridgeProviderOptions, MicroFrontendLifeCycle, MicroFrontendLocation, MicroFrontendProps, QiankunLifeCycle, QiankunProps, QiankunWindow };