Angular升级并添加Module Federation插件后浏览器无法加载应用报错
Angular Module Federation 启动NullInjectorError解决方案
核心排查方向
这个错误是压缩后的依赖注入缺失报错,本质是Module Federation场景下多应用依赖实例不统一、配置未生效、依赖路径解析错误三类问题导致。
具体解决方案
1. 修正webpack配置必填项
你当前的配置里两个核心配置错误,直接修改webpack.config.js:
module.exports = { output: { uniqueName: "mfePOC", publicPath: "auto" // 取消注释,必填,用于Module Federation资源路径解析 }, optimization: { runtimeChunk: 'single' // 从false改成single,Angular 12+ 配合MF必须保留运行时单例 }, plugins: [ new ModuleFederationPlugin({ remotes: { host: { external: "http://localhost:4000/remoteEntry.js" } }, shared:{ "@angular/core": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/common": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/common/http": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/router": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, // 补充缺失的Angular生态共享依赖,避免多实例导致注入上下文不统一 "@angular/animations": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/cdk": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/flex-layout": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/forms": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/material": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "@angular/platform-browser": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "rxjs": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, "zone.js": { singleton: true, strictVersion: false, requiredVersion: 'auto' }, // 修正错误的ag-grid包名,你package.json安装的是ag-grid-enterprise不是@ag-grid-enterprise/all-modules "ag-grid-enterprise": {singleton: true, strictVersion: true}, "subsink": { singleton: true, strictVersion: false }, ...sharedMappings.getDescriptors() } }), sharedMappings.getPlugin() ], };
2. 确认angular.json配置生效
你需要确保angular.json里的构建、启动配置已经替换为Module Federation的builder,否则你写的webpack.config.js不会被加载:
- 找到
projects.<你的项目名>.architect.build.builder,修改为@angular-architects/module-federation:browser - 找到
projects.<你的项目名>.architect.serve.builder,修改为@angular-architects/module-federation:dev-server - 确认build配置里的
customWebpackConfig.path指向你写的webpack.config.js
3. 临时调试定位具体缺失的Provider
如果修改完上述配置还是报错,临时修改angular.json的构建配置打开源码映射、关闭压缩:
{ "projects": { "<你的项目名>": { "architect": { "build": { "options": { "optimization": false, "sourceMap": true } } } } } }
重启服务后报错就会显示具体缺失的Provider名称,而非压缩后的e/t变量,可以针对性补充共享依赖或者检查对应模块的Providers配置。
内容的提问来源于stack exchange,提问作者Mahesh Vemula
相关产品推荐
相关产品推荐

