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

查看 71|回复 6
作者: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);
    });
}
LuckyLauncher   
都用 module 了,直接 import 呢
LuckyLauncher   
import(url).then(m => m.default).then(component => {// 后续处理})
lisongeee   
// 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   
模块联邦?
gkinxin   
https://helmicro.com/hel/
可以试试这个
youyouzi   
联邦模块
您需要登录后才可以回帖 登录 | 立即注册

返回顶部