当我将 React 与 ReactRouter 一起使用时,我可以延迟加载应用程序的入口文件吗?当我进入页面时,我拥有的每个应用程序都有很多对 remoteEntry.js
文件的请求。由于性能原因,我不想一开始就获取它。我想在访问特定应用程序的路径时加载它们。
最佳答案
您需要使用基于 promise 的动态 Remote 。
例如,与其将 Remote 定义为 URL:
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
app1: 'app1@http://localhost:3001/remoteEntry.js',
},
}),
],
};
您可以在 webpack.config.js
中删除此引用并将远程定义为将在运行时解析的 promise :
const loadScope = (url: string, scope: string) => {
const element: any = document.createElement('script');
const promise = new Promise((resolve, reject) => {
element.src = url;
element.type = 'text/javascript';
element.async = true;
element.onload = () => resolve(window[scope]);
element.onerror = reject;
});
document.head.appendChild(element);
promise.finally(() => document.head.removeChild(element));
return promise;
};
const loadModule = async (url: string, scope: string, module: string) => {
try {
const container = await loadScope(url, scope);
await __webpack_init_sharing__('default');
await container.init(__webpack_share_scopes__.default);
const factory = await container.get(module);
return factory();
} catch (error) {
console.error('Error loading module:', error);
throw error;
}
};
const MyApp = React.lazy(() =>
loadModule(
'http://localhost:3001/remoteEntry.js',
'app1',
'./MyApp',
),
);
更多详情可以引用Webpack 5 documentation .
关于reactjs - Webpack 模块联邦延迟加载 remoteEntry.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68123199/