const loadRemote = async () => { return new Promise((resolve, reject) => { script.onload = () => { const remoteModule = window[route.name] if (!remoteModule) { reject(new Error(`Failed to load remote module`)) } else { const remoteComponent = remoteModule[route.name] console.log('-------------') console.log(remoteModule) if (!remoteComponent) { reject(new Error(`Failed to load remote module`)) } else { resolve(remoteComponent) } } } }) } const tmp = { name: route.name, path: route.path, component: loadRemote } router.addRoute('default', tmp)
时间: 2024-02-14 15:29:17 浏览: 193
你的代码看起来几乎是正确的,不过有一点需要注意的是,`loadRemote` 函数应该返回一个异步函数,而非一个 Promise。
下面是修正后的代码示例:
```javascript
const loadRemote = async () => {
return () =>
new Promise((resolve, reject) => {
const script = document.createElement('script');
script.src = `http://localhost:5001/assets/remoteEntry.js`;
script.onload = () => {
const remoteModule = window[route.name];
if (!remoteModule) {
reject(new Error(`Failed to load remote module`));
} else {
const remoteComponent = remoteModule[route.name];
if (!remoteComponent) {
reject(new Error(`Failed to load remote component`));
} else {
resolve(remoteComponent);
}
}
};
script.onerror = () => {
reject(new Error(`Failed to load remote module`));
};
document.head.appendChild(script);
});
};
const tmp = {
name: route.name,
path: route.path,
component: loadRemote
};
router.addRoute('default', tmp);
```
在修正后的代码中,`loadRemote` 函数返回了一个异步函数,该异步函数在执行时会动态加载远程组件,并将加载到的组件作为结果进行 resolve。另外,我还添加了对动态加载脚本失败的错误处理。
请注意,上述代码中的 `route.name` 和 `route.path` 变量是指代你具体的路由名称和路径,你需要根据你的实际情况进行调整。
阅读全文