Angular 14 Module Federation共享npm别名库单例版本匹配问题
解决Angular模块联邦中npm别名库的单例共享版本不匹配问题
问题根源
webpack模块联邦通过模块请求字符串匹配共享模块。你用npm别名配置后,项目中引用的@myRegistry-1-namespace/ui和实际对应的原始包请求npm:@myRegistry-2-namespace/ui@3.0.0被判定为两个不同模块,即便版本一致,也会触发单例模式下的版本校验错误。
解决方案
方案1:统一模块标识映射
在宿主和远程应用的webpack.config.js中,同时配置resolve别名和共享规则,让两个模块请求指向同一个共享实例:
module.exports = { // ...其他配置 resolve: { alias: { '@myRegistry-1-namespace/ui': 'npm:@myRegistry-2-namespace/ui@3.0.0', 'npm:@myRegistry-2-namespace/ui': '@myRegistry-1-namespace/ui' } }, plugins: [ new ModuleFederationPlugin({ // ...宿主/远程的其他配置 shared: { '@myRegistry-1-namespace/ui': { singleton: true, strictVersion: true, requiredVersion: '3.0.0', // 明确指定版本,替代auto packageName: '@myRegistry-2-namespace/ui' // 帮助webpack识别实际包版本 } } }) ] };
方案2:共享配置中绑定同一共享键
若不想修改resolve别名,可在共享配置中为两个模块请求设置相同shareKey,让webpack将它们视为同一共享模块:
module.exports = { plugins: [ new ModuleFederationPlugin({ // ...其他配置 shared: { '@myRegistry-1-namespace/ui': { singleton: true, strictVersion: true, requiredVersion: '3.0.0' }, 'npm:@myRegistry-2-namespace/ui': { singleton: true, strictVersion: true, requiredVersion: '3.0.0', shareKey: '@myRegistry-1-namespace/ui' // 映射到同一共享标识 } } }) ] };
验证步骤
- 在两个项目中执行
npm ls @myRegistry-1-namespace/ui和npm ls @myRegistry-2-namespace/ui,确认安装版本均为3.0.0 - 重启宿主和远程应用的开发服务,检查版本不匹配错误是否消失
内容的提问来源于stack exchange,提问作者mikg
相关产品推荐
相关产品推荐

