如何从网络中加载 React 组件并渲染它?想不到更好的办法了

282 天前
DAGU1182810784  DAGU1182810784

我期望在运行的 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);
    });
}

2163 次点击
所在节点   程序员  程序员
12 条回复
LuckyLauncher
LuckyLauncher
282 天前
都用 module 了,直接 import 呢
LuckyLauncher
LuckyLauncher
282 天前
import(url).then(m => m.default).then(component => {// 后续处理})
lisongeee
lisongeee
282 天前
// 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);
});
}
zhtyytg
zhtyytg
282 天前
模块联邦?
gkinxin
gkinxin
282 天前
https://helmicro.com/hel/
可以试试这个
youyouzi
youyouzi
282 天前
联邦模块
gxvsko
gxvsko
282 天前
DOLLOR
DOLLOR
282 天前
“react 组件”本质不就是一个 function 吗?
你让他们 export 那个 function ,你这边 import 进来,再在你的 jsx 里渲染就好了。
shenyu1996
shenyu1996
282 天前
不考虑兼容性直接原生 es6 的 import 就可以 见 2 楼
xu33
xu33
282 天前
了解一下联邦模块
DAGU1182810784
282 天前
好的,感谢各位的回复,这对我很有帮助
unco020511
282 天前
二楼说了,import 远程模块即可

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1040513

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX