@empjs/bridge-react 0.0.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 ADDED
@@ -0,0 +1,143 @@
1
+ # EMP Bridge React
2
+
3
+ EMP Bridge React 是一个用于跨 React 版本组件通信的桥接工具,它解决了不同 React 版本之间组件共享和通信的问题。
4
+
5
+ ## 功能特点
6
+
7
+ - 支持不同 React 版本(16/17/18/19)之间的组件共享
8
+ - 提供简单的 API 用于生产者和消费者之间的通信
9
+ - 自动处理 React 不同版本的渲染和卸载方法差异
10
+ - 支持异步加载组件
11
+
12
+ ## 安装
13
+
14
+ ```bash
15
+ # 使用 npm
16
+ npm install @empjs/bridge-react
17
+
18
+ # 使用 yarn
19
+ yarn add @empjs/bridge-react
20
+
21
+ # 使用 pnpm
22
+ pnpm add @empjs/bridge-react
23
+ ```
24
+
25
+ ## 基本用法
26
+
27
+ ### 生产者(导出组件的应用)
28
+
29
+ ```tsx
30
+ // 在 React 16/17 应用中
31
+ import React from 'react';
32
+ import { createBridgeComponent } from '@empjs/bridge-react';
33
+
34
+ // 创建要共享的组件
35
+ const MyComponent = (props) => {
36
+ return <div>Hello from React 16/17! {props.message}</div>;
37
+ };
38
+
39
+ // 导出桥接组件
40
+ export default createBridgeComponent(MyComponent, {
41
+ React,
42
+ ReactDOM: require('react-dom'),
43
+ // React 18+ 才有 createRoot
44
+ // createRoot: require('react-dom/client').createRoot
45
+ });
46
+ ```
47
+
48
+ ### 消费者(使用组件的应用)
49
+
50
+ ```tsx
51
+ // 在 React 18/19 应用中
52
+ import React from 'react';
53
+ import { createRemoteAppComponent } from '@empjs/bridge-react';
54
+
55
+ // 导入远程组件(可以是动态导入)
56
+ import RemoteComponent from 'remote-app/MyComponent';
57
+
58
+ // 创建可在当前 React 版本中使用的组件
59
+ const BridgedComponent = createRemoteAppComponent(
60
+ RemoteComponent,
61
+ {
62
+ React,
63
+ ReactDOM: require('react-dom'),
64
+ createRoot: require('react-dom/client').createRoot
65
+ },
66
+ {
67
+ onError: (error) => console.error('Failed to load component:', error)
68
+ }
69
+ );
70
+
71
+ // 在应用中使用
72
+ function App() {
73
+ return (
74
+ <div>
75
+ <h1>My App (React 18/19)</h1>
76
+ <BridgedComponent message="Passed from React 18/19" />
77
+ </div>
78
+ );
79
+ }
80
+ ```
81
+
82
+ ## API 参考
83
+
84
+ ### createBridgeComponent
85
+
86
+ 用于生产者包装应用级别导出模块。
87
+
88
+ ```typescript
89
+ function createBridgeComponent(
90
+ Component: React.ComponentType<any>,
91
+ options: {
92
+ React: any;
93
+ ReactDOM: any;
94
+ createRoot?: Function;
95
+ }
96
+ ): BridgeProvider
97
+ ```
98
+
99
+ 参数:
100
+ - `Component`: 要导出的 React 组件
101
+ - `options`: React 相关配置
102
+ - `React`: React 实例
103
+ - `ReactDOM`: ReactDOM 实例
104
+ - `createRoot`: (可选) React 18+ 的 createRoot 方法
105
+
106
+ ### createRemoteAppComponent
107
+
108
+ 用于消费者加载应用级别模块。
109
+
110
+ ```typescript
111
+ function createRemoteAppComponent(
112
+ component: ComponentProvider,
113
+ reactOptions: {
114
+ React: any;
115
+ ReactDOM: any;
116
+ createRoot?: Function;
117
+ },
118
+ options?: {
119
+ onError?: (error: Error) => void;
120
+ }
121
+ ): React.ComponentType<any>
122
+ ```
123
+
124
+ 参数:
125
+ - `component`: 组件提供者函数,可以是同步或异步的
126
+ - `reactOptions`: 当前应用的 React 相关配置
127
+ - `React`: React 实例
128
+ - `ReactDOM`: ReactDOM 实例
129
+ - `createRoot`: (可选) React 18+ 的 createRoot 方法
130
+ - `options`: (可选) 额外配置
131
+ - `onError`: 错误处理回调函数
132
+
133
+ ## 使用场景
134
+
135
+ 1. 微前端架构中不同 React 版本的应用集成
136
+ 2. 逐步升级大型 React 应用时的版本兼容
137
+ 3. 共享组件库到不同 React 版本的项目中
138
+
139
+ ## 注意事项
140
+
141
+ - 确保正确提供对应版本的 React 和 ReactDOM 实例
142
+ - 对于 React 18+,需要提供 createRoot 方法
143
+ - 组件间通信仅限于 props 传递,不支持 Context API 跨版本共享
package/dist/index.cjs ADDED
@@ -0,0 +1,152 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, definition)=>{
5
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
6
+ enumerable: true,
7
+ get: definition[key]
8
+ });
9
+ };
10
+ })();
11
+ (()=>{
12
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
13
+ })();
14
+ (()=>{
15
+ __webpack_require__.r = (exports1)=>{
16
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
17
+ value: 'Module'
18
+ });
19
+ Object.defineProperty(exports1, '__esModule', {
20
+ value: true
21
+ });
22
+ };
23
+ })();
24
+ var __webpack_exports__ = {};
25
+ __webpack_require__.r(__webpack_exports__);
26
+ __webpack_require__.d(__webpack_exports__, {
27
+ createBridgeComponent: ()=>createBridgeComponent,
28
+ createRemoteAppComponent: ()=>createRemoteAppComponent,
29
+ default: ()=>__WEBPACK_DEFAULT_EXPORT__
30
+ });
31
+ function createBridgeComponent(Component, options) {
32
+ const { React, ReactDOM, createRoot } = options;
33
+ const hasCreateRoot = 'function' == typeof createRoot;
34
+ return function() {
35
+ const rootMap = new Map();
36
+ const render = (dom, props)=>{
37
+ try {
38
+ const element = React.createElement(Component, props || {});
39
+ const existingRoot = rootMap.get(dom);
40
+ if (existingRoot) {
41
+ if (hasCreateRoot && 'render' in existingRoot) existingRoot.render(element);
42
+ else if (ReactDOM.render) ReactDOM.render(element, dom);
43
+ } else if (hasCreateRoot && createRoot) {
44
+ const root = createRoot(dom);
45
+ root.render(element);
46
+ rootMap.set(dom, root);
47
+ } else if (ReactDOM.render) {
48
+ ReactDOM.render(element, dom);
49
+ rootMap.set(dom, dom);
50
+ }
51
+ } catch (error) {
52
+ console.error('[EMP-ERROR] Failed to render/update component', error);
53
+ throw error;
54
+ }
55
+ };
56
+ const destroy = (dom)=>{
57
+ const root = rootMap.get(dom);
58
+ if (!root) return;
59
+ try {
60
+ if (hasCreateRoot && 'unmount' in root) root.unmount();
61
+ else if (ReactDOM.unmountComponentAtNode) ReactDOM.unmountComponentAtNode(dom);
62
+ rootMap.delete(dom);
63
+ } catch (error) {
64
+ console.error('[EMP-ERROR] Failed to unmount component', error);
65
+ }
66
+ };
67
+ return {
68
+ render,
69
+ destroy
70
+ };
71
+ };
72
+ }
73
+ function createRemoteAppComponent(component, reactOptions, options = {}) {
74
+ if (!component) throw new Error('createRemoteAppComponent: component parameter cannot be empty');
75
+ const { React } = reactOptions;
76
+ class RemoteAppComponent extends React.Component {
77
+ containerRef = React.createRef();
78
+ provider = null;
79
+ providerInfo = null;
80
+ isMounted = false;
81
+ constructor(props){
82
+ super(props);
83
+ this.loadComponent();
84
+ }
85
+ async loadComponent() {
86
+ try {
87
+ if ('function' == typeof component) {
88
+ const result = component();
89
+ if (result instanceof Promise) {
90
+ const module = await result;
91
+ this.providerInfo = module.default;
92
+ } else this.providerInfo = component;
93
+ }
94
+ if (this.isMounted && this.containerRef.current) this.renderComponent();
95
+ } catch (error) {
96
+ if (options.onError) options.onError(error);
97
+ console.error('[EMP-ERROR] Failed to load component', error);
98
+ }
99
+ }
100
+ renderComponent() {
101
+ if (!this.providerInfo || !this.containerRef.current) return;
102
+ try {
103
+ if (!this.provider) this.provider = this.providerInfo();
104
+ this.provider.render(this.containerRef.current, this.props);
105
+ } catch (error) {
106
+ console.error('[EMP-ERROR] Failed to render component', error);
107
+ }
108
+ }
109
+ unmountComponent() {
110
+ if (this.provider && this.containerRef.current) try {
111
+ this.provider.destroy(this.containerRef.current);
112
+ this.provider = null;
113
+ } catch (error) {
114
+ console.error('[EMP-ERROR] Failed to unmount component', error);
115
+ }
116
+ }
117
+ componentDidMount() {
118
+ this.isMounted = true;
119
+ if (this.providerInfo) this.renderComponent();
120
+ }
121
+ componentDidUpdate() {
122
+ if (this.provider && this.containerRef.current) this.provider.render(this.containerRef.current, this.props);
123
+ }
124
+ componentWillUnmount() {
125
+ this.isMounted = false;
126
+ const cleanup = ()=>this.unmountComponent();
127
+ if ('undefined' != typeof window && window.requestAnimationFrame) window.requestAnimationFrame(cleanup);
128
+ else setTimeout(cleanup, 0);
129
+ }
130
+ render() {
131
+ return React.createElement('div', {
132
+ ref: this.containerRef
133
+ });
134
+ }
135
+ }
136
+ return RemoteAppComponent;
137
+ }
138
+ const __WEBPACK_DEFAULT_EXPORT__ = {
139
+ createBridgeComponent,
140
+ createRemoteAppComponent
141
+ };
142
+ exports.createBridgeComponent = __webpack_exports__.createBridgeComponent;
143
+ exports.createRemoteAppComponent = __webpack_exports__.createRemoteAppComponent;
144
+ exports["default"] = __webpack_exports__["default"];
145
+ for(var __webpack_i__ in __webpack_exports__)if (-1 === [
146
+ "createBridgeComponent",
147
+ "createRemoteAppComponent",
148
+ "default"
149
+ ].indexOf(__webpack_i__)) exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
150
+ Object.defineProperty(exports, '__esModule', {
151
+ value: true
152
+ });
@@ -0,0 +1,29 @@
1
+ export interface BridgeProviderReturn {
2
+ render: (dom: HTMLElement, props?: Record<string, any>) => void;
3
+ destroy: (dom: HTMLElement) => void;
4
+ }
5
+ export type BridgeProvider = () => BridgeProviderReturn;
6
+ export type AsyncBridgeProvider = () => Promise<{
7
+ default: BridgeProvider;
8
+ }>;
9
+ export type ComponentProvider = BridgeProvider | AsyncBridgeProvider;
10
+ interface ReactOptions {
11
+ React?: any;
12
+ ReactDOM?: any;
13
+ createRoot?: any;
14
+ }
15
+ /**
16
+ * Create bridge component - for producer to wrap application-level export modules
17
+ */
18
+ export declare function createBridgeComponent(Component: any, options: ReactOptions): BridgeProvider;
19
+ /**
20
+ * Create remote app component - for consumer to load application-level modules
21
+ */
22
+ export declare function createRemoteAppComponent(component: ComponentProvider, reactOptions: ReactOptions, options?: {
23
+ onError?: (error: Error) => void;
24
+ }): any;
25
+ declare const _default: {
26
+ createBridgeComponent: typeof createBridgeComponent;
27
+ createRemoteAppComponent: typeof createRemoteAppComponent;
28
+ };
29
+ export default _default;
package/dist/index.js ADDED
@@ -0,0 +1,112 @@
1
+ function createBridgeComponent(Component, options) {
2
+ const { React, ReactDOM, createRoot } = options;
3
+ const hasCreateRoot = 'function' == typeof createRoot;
4
+ return function() {
5
+ const rootMap = new Map();
6
+ const render = (dom, props)=>{
7
+ try {
8
+ const element = React.createElement(Component, props || {});
9
+ const existingRoot = rootMap.get(dom);
10
+ if (existingRoot) {
11
+ if (hasCreateRoot && 'render' in existingRoot) existingRoot.render(element);
12
+ else if (ReactDOM.render) ReactDOM.render(element, dom);
13
+ } else if (hasCreateRoot && createRoot) {
14
+ const root = createRoot(dom);
15
+ root.render(element);
16
+ rootMap.set(dom, root);
17
+ } else if (ReactDOM.render) {
18
+ ReactDOM.render(element, dom);
19
+ rootMap.set(dom, dom);
20
+ }
21
+ } catch (error) {
22
+ console.error('[EMP-ERROR] Failed to render/update component', error);
23
+ throw error;
24
+ }
25
+ };
26
+ const destroy = (dom)=>{
27
+ const root = rootMap.get(dom);
28
+ if (!root) return;
29
+ try {
30
+ if (hasCreateRoot && 'unmount' in root) root.unmount();
31
+ else if (ReactDOM.unmountComponentAtNode) ReactDOM.unmountComponentAtNode(dom);
32
+ rootMap.delete(dom);
33
+ } catch (error) {
34
+ console.error('[EMP-ERROR] Failed to unmount component', error);
35
+ }
36
+ };
37
+ return {
38
+ render,
39
+ destroy
40
+ };
41
+ };
42
+ }
43
+ function createRemoteAppComponent(component, reactOptions, options = {}) {
44
+ if (!component) throw new Error('createRemoteAppComponent: component parameter cannot be empty');
45
+ const { React } = reactOptions;
46
+ class RemoteAppComponent extends React.Component {
47
+ containerRef = React.createRef();
48
+ provider = null;
49
+ providerInfo = null;
50
+ isMounted = false;
51
+ constructor(props){
52
+ super(props);
53
+ this.loadComponent();
54
+ }
55
+ async loadComponent() {
56
+ try {
57
+ if ('function' == typeof component) {
58
+ const result = component();
59
+ if (result instanceof Promise) {
60
+ const module = await result;
61
+ this.providerInfo = module.default;
62
+ } else this.providerInfo = component;
63
+ }
64
+ if (this.isMounted && this.containerRef.current) this.renderComponent();
65
+ } catch (error) {
66
+ if (options.onError) options.onError(error);
67
+ console.error('[EMP-ERROR] Failed to load component', error);
68
+ }
69
+ }
70
+ renderComponent() {
71
+ if (!this.providerInfo || !this.containerRef.current) return;
72
+ try {
73
+ if (!this.provider) this.provider = this.providerInfo();
74
+ this.provider.render(this.containerRef.current, this.props);
75
+ } catch (error) {
76
+ console.error('[EMP-ERROR] Failed to render component', error);
77
+ }
78
+ }
79
+ unmountComponent() {
80
+ if (this.provider && this.containerRef.current) try {
81
+ this.provider.destroy(this.containerRef.current);
82
+ this.provider = null;
83
+ } catch (error) {
84
+ console.error('[EMP-ERROR] Failed to unmount component', error);
85
+ }
86
+ }
87
+ componentDidMount() {
88
+ this.isMounted = true;
89
+ if (this.providerInfo) this.renderComponent();
90
+ }
91
+ componentDidUpdate() {
92
+ if (this.provider && this.containerRef.current) this.provider.render(this.containerRef.current, this.props);
93
+ }
94
+ componentWillUnmount() {
95
+ this.isMounted = false;
96
+ const cleanup = ()=>this.unmountComponent();
97
+ if ('undefined' != typeof window && window.requestAnimationFrame) window.requestAnimationFrame(cleanup);
98
+ else setTimeout(cleanup, 0);
99
+ }
100
+ render() {
101
+ return React.createElement('div', {
102
+ ref: this.containerRef
103
+ });
104
+ }
105
+ }
106
+ return RemoteAppComponent;
107
+ }
108
+ const src = {
109
+ createBridgeComponent,
110
+ createRemoteAppComponent
111
+ };
112
+ export { createBridgeComponent, createRemoteAppComponent, src as default };
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@empjs/bridge-react",
3
+ "version": "0.0.1",
4
+ "description": "emp react bridgeeact",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "files": [
8
+ "dist"
9
+ ],
10
+ "maintainers": [
11
+ "xuhongbin",
12
+ "ckken",
13
+ "doerme",
14
+ "ron0115"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/empjs/emp.git",
19
+ "directory": "packages/bridge-react"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "main": "dist/index.js",
25
+ "types": "dist/index.d.ts",
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ },
32
+ "require": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.cjs"
35
+ }
36
+ }
37
+ },
38
+ "engines": {
39
+ "node": ">=16.0.0"
40
+ },
41
+ "author": "Ken",
42
+ "dependencies": {},
43
+ "devDependencies": {},
44
+ "scripts": {
45
+ "dev": "rslib build --watch --env-mode development",
46
+ "build": "rslib build"
47
+ }
48
+ }