Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: mount bridge api to host instance #3234

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/small-bats-leave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@module-federation/bridge-react': patch
---

feat: mount bridge api to module instance
20 changes: 13 additions & 7 deletions apps/router-demo/router-host-2000/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,17 @@ import { useRef, useEffect, ForwardRefExoticComponent } from 'react';
import { Route, Routes, useLocation } from 'react-router-dom';
import { init, loadRemote } from '@module-federation/enhanced/runtime';
import { RetryPlugin } from '@module-federation/retry-plugin';
import { createRemoteComponent } from '@module-federation/bridge-react';
import BridgeReactPlugin from '@module-federation/bridge-react/plugin';
import Navigation from './navigation';
import Detail from './pages/Detail';
import Home from './pages/Home';
import './App.css';

init({
const hostInstance = init({
name: 'federation_consumer',
remotes: [],
plugins: [
BridgeReactPlugin(),
RetryPlugin({
fetch: {
url: 'http://localhost:2008/not-exist-mf-manifest.json',
Expand Down Expand Up @@ -46,32 +47,37 @@ const FallbackErrorComp = (info: any) => {

const FallbackComp = <div data-test-id="loading">loading...</div>;

const Remote1App = createRemoteComponent({
// @ts-ignore
const Remote1App = hostInstance.createRemoteComponent({
loader: () => loadRemote('remote1/export-app'),
fallback: FallbackErrorComp,
loading: FallbackComp,
});

const Remote2App = createRemoteComponent({
// @ts-ignore
const Remote2App = hostInstance.createRemoteComponent({
loader: () => import('remote2/export-app'),
export: 'provider',
fallback: FallbackErrorComp,
loading: FallbackComp,
});

const Remote3App = createRemoteComponent({
// @ts-ignore
const Remote3App = hostInstance.createRemoteComponent({
loader: () => loadRemote('remote3/export-app'),
fallback: FallbackErrorComp,
loading: FallbackComp,
});

const RemoteRenderErrorApp = createRemoteComponent({
// @ts-ignore
const RemoteRenderErrorApp = hostInstance.createRemoteComponent({
loader: () => loadRemote('remote-render-error/export-app'),
fallback: FallbackErrorComp,
loading: FallbackComp,
}) as ForwardRefExoticComponent<unknown>;

const RemoteResourceErrorApp = createRemoteComponent({
// @ts-ignore
const RemoteResourceErrorApp = hostInstance.createRemoteComponent({
loader: () => loadRemote('remote-resource-error/export-app'),
fallback: FallbackErrorComp,
loading: FallbackComp,
Expand Down
3 changes: 3 additions & 0 deletions apps/router-demo/router-remote1-2001/rsbuild.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ export default defineConfig({
pluginReact(),
pluginModuleFederation({
name: 'remote1',
runtimePlugins: [
require.resolve('@module-federation/bridge-react/plugin'),
],
exposes: {
'./button': './src/button.tsx',
'./export-app': './src/export-App.tsx',
Expand Down
7 changes: 5 additions & 2 deletions apps/router-demo/router-remote1-2001/src/export-App.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import React from 'react';
import { getInstance } from '@module-federation/enhanced/runtime';
import App from './App';
import { createBridgeComponent } from '@module-federation/bridge-react';

const provider = createBridgeComponent({
const hostInstance = getInstance();

// @ts-ignore
const provider = hostInstance.createBridgeComponent({
rootComponent: App,
});

Expand Down
21 changes: 13 additions & 8 deletions packages/bridge/bridge-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,29 +12,34 @@
"directory": "packages/bridge-react"
},
"type": "module",
"main": "./dist/index.cjs.js",
"main": "./dist/index.js",
"module": "./dist/index.es.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.es.js",
"require": "./dist/index.cjs.js"
"require": "./dist/index.js"
},
"./plugin": {
"types": "./dist/plugin.d.ts",
"import": "./dist/plugin.es.js",
"require": "./dist/plugin.js"
},
"./router": {
"types": "./dist/router.d.ts",
"import": "./dist/router.es.js",
"require": "./dist/router.cjs.js"
"require": "./dist/router.js"
},
"./router-v5": {
"types": "./dist/router-v5.d.ts",
"import": "./dist/router-v5.es.js",
"require": "./dist/router-v5.cjs.js"
"require": "./dist/router-v5.js"
},
"./router-v6": {
"types": "./dist/router-v6.d.ts",
"import": "./dist/router-v6.es.js",
"require": "./dist/router-v6.cjs.js"
"require": "./dist/router-v6.js"
},
"./*": "./*"
},
Expand All @@ -47,8 +52,7 @@
"@loadable/component": "^5.16.4",
"@module-federation/bridge-shared": "workspace:*",
"@module-federation/sdk": "workspace:*",
"react-error-boundary": "^4.0.13",
"@module-federation/runtime": "workspace:*"
"react-error-boundary": "^4.0.13"
},
"peerDependencies": {
"react": ">=16.9.0",
Expand All @@ -68,6 +72,7 @@
"react-router-dom": "6.22.3",
"typescript": "^5.2.2",
"vite": "^5.2.14",
"vite-plugin-dts": "^3.9.1"
"vite-plugin-dts": "^3.9.1",
"@module-federation/enhanced": "workspace:*"
}
}
20 changes: 12 additions & 8 deletions packages/bridge/bridge-react/src/create.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { forwardRef } from 'react';
import type { FederationHost } from '@module-federation/enhanced/runtime';
import {
ErrorBoundary,
ErrorBoundaryPropsWithComponent,
Expand All @@ -18,12 +19,17 @@ interface RemoteModule {
};
}

function createLazyRemoteComponent<T, E extends keyof T>(info: {
type LazyRemoteComponentInfo<T, E extends keyof T> = {
loader: () => Promise<T>;
loading: React.ReactNode;
fallback: ErrorBoundaryPropsWithComponent['FallbackComponent'];
export?: E;
}) {
instance?: FederationHost;
};

function createLazyRemoteComponent<T, E extends keyof T>(
info: LazyRemoteComponentInfo<T, E>,
) {
const exportName = info?.export || 'default';
return React.lazy(async () => {
LoggerInstance.log(`createRemoteComponent LazyComponent create >>>`, {
Expand Down Expand Up @@ -58,6 +64,7 @@ function createLazyRemoteComponent<T, E extends keyof T>(info: {
exportName={info.export || 'default'}
fallback={info.fallback}
ref={ref}
instance={info.instance}
{...props}
/>
);
Expand All @@ -83,12 +90,9 @@ function createLazyRemoteComponent<T, E extends keyof T>(info: {
});
}

export function createRemoteComponent<T, E extends keyof T>(info: {
loader: () => Promise<T>;
loading: React.ReactNode;
fallback: ErrorBoundaryPropsWithComponent['FallbackComponent'];
export?: E;
}) {
export function createRemoteComponent<T, E extends keyof T>(
info: LazyRemoteComponentInfo<T, E>,
) {
type ExportType = T[E] extends (...args: any) => any
? ReturnType<T[E]>
: never;
Expand Down
2 changes: 2 additions & 0 deletions packages/bridge/bridge-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export { createRemoteComponent } from './create';
export { createBridgeComponent } from './provider';
export { default as BridgeReactPlugin } from './plugin';

export type {
ProviderParams,
RenderFnParams,
Expand Down
31 changes: 31 additions & 0 deletions packages/bridge/bridge-react/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';
import { createRemoteComponent } from './create';
import { createBridgeComponent } from './provider';

function BridgeReactPlugin(): FederationRuntimePlugin {
return {
name: 'bridge-react-plugin',
beforeInit(args) {
const originalCreateRemoteComponent = createRemoteComponent;
// @ts-ignore
args.origin.createRemoteComponent = function (info) {
return originalCreateRemoteComponent({
...info,
instance: args.origin,
});
};

const originalCreateBridgeComponentt = createBridgeComponent; // 保存原始函数
// @ts-ignore
args.origin.createBridgeComponent = function (info) {
return originalCreateBridgeComponentt({
...info,
instance: args.origin,
});
};
return args;
},
};
}

export default BridgeReactPlugin;
16 changes: 10 additions & 6 deletions packages/bridge/bridge-react/src/provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import type {
import { ErrorBoundary } from 'react-error-boundary';
import { RouterContext } from './context';
import { LoggerInstance, atLeastReact18 } from './utils';
import { getInstance } from '@module-federation/runtime';
import type { FederationHost } from '@module-federation/enhanced/runtime';

type RenderParams = RenderFnParams & {
[key: string]: unknown;
Expand All @@ -26,13 +26,17 @@ type ProviderFnParams<T> = {
App: React.ReactElement,
id?: HTMLElement | string,
) => RootType | Promise<RootType>;
instance?: FederationHost;
};

export function createBridgeComponent<T>(bridgeInfo: ProviderFnParams<T>) {
return () => {
const rootMap = new Map<any, RootType>();
const instance = getInstance();
LoggerInstance.log(`createBridgeComponent remote instance`, instance);
const { instance } = bridgeInfo;
LoggerInstance.log(
`createBridgeComponent instance from props >>>`,
instance,
);

const RawComponent = (info: { propsInfo: T; appInfo: ProviderParams }) => {
const { appInfo, propsInfo, ...restProps } = info;
Expand Down Expand Up @@ -95,15 +99,13 @@ export function createBridgeComponent<T>(bridgeInfo: ProviderFnParams<T>) {
const renderFn = bridgeInfo?.render || ReactDOM.render;
renderFn?.(rootComponentWithErrorBoundary, info.dom);
}

instance?.bridgeHook?.lifecycle?.afterBridgeRender?.emit(info) || {};
},

async destroy(info: DestroyParams) {
LoggerInstance.log(`createBridgeComponent destroy Info`, {
dom: info.dom,
});

instance?.bridgeHook?.lifecycle?.beforeBridgeDestroy?.emit(info);

// call destroy function
Expand All @@ -115,7 +117,9 @@ export function createBridgeComponent<T>(bridgeInfo: ProviderFnParams<T>) {
ReactDOM.unmountComponentAtNode(info.dom);
}

instance?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit(info);
(instance as any)?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit(
info,
);
},
rawComponent: bridgeInfo.rootComponent,
__BRIDGE_FN__: (_args: T) => {},
Expand Down
19 changes: 9 additions & 10 deletions packages/bridge/bridge-react/src/remote/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import type { ProviderParams } from '@module-federation/bridge-shared';
import { dispatchPopstateEnv } from '@module-federation/bridge-shared';
import { ErrorBoundaryPropsWithComponent } from 'react-error-boundary';
import { LoggerInstance, pathJoin, getRootDomDefaultClassName } from '../utils';
import { getInstance } from '@module-federation/runtime';
import type { FederationHost } from '@module-federation/enhanced/runtime';

declare const __APP_VERSION__: string;
export interface RenderFnParams extends ProviderParams {
Expand All @@ -34,6 +34,7 @@ interface RemoteAppParams {
providerInfo: NonNullable<RemoteModule['provider']>;
exportName: string | number | symbol;
fallback: ErrorBoundaryPropsWithComponent['FallbackComponent'];
instance: FederationHost;
}

const RemoteAppWrapper = forwardRef(function (
Expand All @@ -50,6 +51,7 @@ const RemoteAppWrapper = forwardRef(function (
className,
style,
fallback,
instance,
...resProps
} = props;

Expand All @@ -60,8 +62,7 @@ const RemoteAppWrapper = forwardRef(function (

const renderDom: React.MutableRefObject<HTMLElement | null> = useRef(null);
const providerInfoRef = useRef<any>(null);
const hostInstance = getInstance();
LoggerInstance.log(`RemoteAppWrapper hostInstance >>>`, hostInstance);
LoggerInstance.log(`RemoteAppWrapper instance from props >>>`, instance);

useEffect(() => {
const renderTimeout = setTimeout(() => {
Expand All @@ -84,18 +85,16 @@ const RemoteAppWrapper = forwardRef(function (

LoggerInstance.log(
`createRemoteComponent LazyComponent hostInstance >>>`,
hostInstance,
instance,
);
const beforeBridgeRenderRes =
hostInstance?.bridgeHook?.lifecycle?.beforeBridgeRender?.emit(
instance?.bridgeHook?.lifecycle?.beforeBridgeRender?.emit(
renderProps,
) || {};
// @ts-ignore
renderProps = { ...renderProps, ...beforeBridgeRenderRes.extraProps };
providerReturn.render(renderProps);
hostInstance?.bridgeHook?.lifecycle?.afterBridgeRender?.emit(
renderProps,
);
instance?.bridgeHook?.lifecycle?.afterBridgeRender?.emit(renderProps);
});

return () => {
Expand All @@ -107,7 +106,7 @@ const RemoteAppWrapper = forwardRef(function (
{ moduleName, basename, dom: renderDom.current },
);

hostInstance?.bridgeHook?.lifecycle?.beforeBridgeDestroy?.emit({
instance?.bridgeHook?.lifecycle?.beforeBridgeDestroy?.emit({
moduleName,
dom: renderDom.current,
basename,
Expand All @@ -121,7 +120,7 @@ const RemoteAppWrapper = forwardRef(function (
dom: renderDom.current,
});

hostInstance?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit({
instance?.bridgeHook?.lifecycle?.afterBridgeDestroy?.emit({
moduleName,
dom: renderDom.current,
basename,
Expand Down
5 changes: 3 additions & 2 deletions packages/bridge/bridge-react/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ export default defineConfig({
lib: {
entry: {
index: path.resolve(__dirname, 'src/index.ts'),
plugin: path.resolve(__dirname, 'src/plugin.ts'),
router: path.resolve(__dirname, 'src/router.tsx'),
'router-v5': path.resolve(__dirname, 'src/router-v5.tsx'),
'router-v6': path.resolve(__dirname, 'src/router-v6.tsx'),
},
formats: ['cjs', 'es'],
fileName: (format, entryName) => `${entryName}.${format}.js`,
fileName: (format, entryName) =>
`${entryName}.${format.replace('cjs', '')}.js`,
},
rollupOptions: {
external: [
Expand All @@ -36,7 +38,6 @@ export default defineConfig({
'react-router-dom/',
'react-router-dom/index.js',
'react-router-dom/dist/index.js',
'@module-federation/runtime',
],
plugins: [
{
Expand Down
Loading
Loading