
我期望在运行的 React 程序中,通过网络加载 React 组件并使用。有什么可行的方案嘛?
比如我自己运行了一个 React 应用 A ,然后其他人开发了一个 React 组件 B ,组件 B 通过 webpack 或 vite 打包后编译成了纯 js (可能有使用 esmodule )并放在了服务器上的某个位置。 现在,我在应用 A 中直接使用网络请求组件 B ,我希望能拿到 B 中导出的模块,并可以持有它,以决定在合适的时候渲染 B 组件。
要达到这样的效果,有什么可行的方案嘛?
我使用这种方式,但是感觉并不优雅,重要的是它加载之后就立即在模块作用域内执行了,我并不能直接持有 B 组件的导出,进而无法在合适的时候使用 B
function loadRemoteModule(url: string) { return new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = url; script.type = 'module'; script.Onload= () => { // 模块加载成功 resolve(null); }; script.Onerror= () => { // 模块加载失败 reject(new Error(`Failed to load module from ${url}`)); }; document.head.appendChild(script); }); } 1 LuckyLauncher 2024-05-14 10:22:52 +08:00 都用 module 了,直接 import 呢 |
2 LuckyLauncher 2024-05-14 10:24:16 +08:00 import(url).then(m => m.default).then(compOnent=> {// 后续处理}) |
3 lisongeee 2024-05-14 10:25:01 +08:00 // esm async function loadRemoteModule(url: string) { return await import(url).then(mod=>mod.default) } // iife/umd async function loadRemoteModule(url: string, exportGetter:()=>any) { return await new Promise((resolve, reject) => { const script = document.createElement('script'); script.src = url; script.Onload= () => { resolve(exportGetter()); document.head.removeChild(script) }; script.Onerror= () => { // 模块加载失败 reject(new Error(`Failed to load script from ${url}`)); document.head.removeChild(script) }; document.head.appendChild(script); }); } |
4 zhtyytg 2024-05-14 10:38:02 +08:00 模块联邦? |
5 gkinxin 2024-05-14 11:12:16 +08:00 https://helmicro.com/hel/ 可以试试这个 |
6 youyouzi 2024-05-14 11:31:00 +08:00 联邦模块 |
7 gxvsko 2024-05-14 12:06:58 +08:00 |
8 AV1 2024-05-14 12:10:09 +08:00 “react 组件”本质不就是一个 function 吗? 你让他们 export 那个 function ,你这边 import 进来,再在你的 jsx 里渲染就好了。 |
9 shenyu1996 2024-05-14 12:25:55 +08:00 via Android 不考虑兼容性直接原生 es6 的 import 就可以 见 2 楼 |
10 xu33 2024-05-14 12:47:36 +08:00 了解一下联邦模块 |
11 DAGU1182810784 OP 好的,感谢各位的回复,这对我很有帮助 |
12 unco020511 2024-05-14 15:38:12 +08:00 二楼说了,import 远程模块即可 |