Angular12 Module Federation运行测试报共享模块无法即时消费如何配置?
报错原因与解决方案
这个错误是因为你在代码顶层同步导入了被Module Federation标记为共享的模块,Webpack尚未完成共享模块初始化就尝试加载该模块导致的。你可以通过两种方式解决:
方法1:共享模块配置eager属性
找到项目中的Module Federation插件配置文件(通常是根目录下的webpack.config.js,使用@angular-architects/module-federation的项目默认是该配置路径),在shared字段下为所有共享依赖添加eager: true配置:
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin'); module.exports = { plugins: [ new ModuleFederationPlugin({ name: '你的应用标识', filename: 'remoteEntry.js', // 暴露组件/路由的配置 exposes: {}, // 远程应用引用配置 remotes: {}, shared: { '@angular/core': { singleton: true, strictVersion: true, eager: true }, '@angular/common': { singleton: true, strictVersion: true, eager: true }, '@angular/router': { singleton: true, strictVersion: true, eager: true }, '@angular/platform-browser': { singleton: true, strictVersion: true, eager: true }, 'rxjs': { singleton: true, strictVersion: true, eager: true }, // 其他共享依赖、或者报错编号5487对应的业务共享模块,都在此处添加eager: true配置 } }) ] }
配置eager: true后,共享模块会直接打包到当前应用的入口bundle中,不会走异步加载逻辑,可直接解决初始化顺序问题。
注意:如果不知道报错编号5487对应的模块,可以在webpack编译输出的stats日志中搜索该数字,即可得到对应模块的路径,补到shared配置中即可
方法2:异步启动应用(无需配置eager)
如果不想将所有共享模块都设置为eager模式,你可以拆分Angular应用的启动逻辑,等共享模块初始化完成后再异步启动应用:
- 新建
src/bootstrap.ts文件,将原main.ts中的启动逻辑迁移进去:
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app/app.module'; export function bootstrapApp() { return platformBrowserDynamic() .bootstrapModule(AppModule) .catch(err => console.error(err)); }
- 修改
src/main.ts为异步加载启动逻辑:
import('./bootstrap').then(module => module.bootstrapApp());
验证步骤
- 配置完成后重启本地服务、或者重新执行测试命令
- 检查报错是否消失,若仍有同类型不同编号的报错,参照方法1补充对应模块的eager配置即可
内容的提问来源于stack exchange,提问作者Tony Brasunas
相关产品推荐
相关产品推荐

