She*_*d25 5 reactjs webpack react-router micro-frontend webpack-module-federation
当我将 React 与 ReactRouter 结合使用时,我可以延迟加载应用程序的入口文件吗?remoteEntry.js当我进入页面时,我拥有的每个应用程序都有很多文件请求。由于性能原因,我不想一开始就获取它。我想在访问特定应用程序的路线时加载它们。
您需要使用基于承诺的动态遥控器。
例如,不要将远程定义为 URL:
module.exports = {
plugins: [
new ModuleFederationPlugin({
name: 'host',
remotes: {
app1: 'app1@http://localhost:3001/remoteEntry.js',
},
}),
],
};
Run Code Online (Sandbox Code Playgroud)
您可以删除此引用webpack.config.js并将远程定义为将在运行时解析的承诺:
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',
),
);
Run Code Online (Sandbox Code Playgroud)
更多详细信息,您可以参考Webpack 5 文档。
use*_*059 -1
new ModuleFederationPlugin({
name: 'reactParent',
filename: 'remoteEntry.js',
remotes: {
reactChild: 'reactChild@/reactChild/remoteEntry.js',
svelteChild: 'svelteChild@/svelteChild/remoteEntry.js',
vueChild: 'vueChild@/vueChild/remoteEntry.js'
}
})
Run Code Online (Sandbox Code Playgroud)
将remoteEntry.js 文件的路径放入Webpack 配置中即可完成工作。在此示例中,我的应用程序设置为将请求代理到微前端,因此 /reactChild 被代理到特定应用程序运行的位置。
| 归档时间: |
|
| 查看次数: |
6351 次 |
| 最近记录: |