Module Federation Plugin中SharedMappings无法找到共享认证库问题
问题场景
在微前端Webpack配置中使用SharedMappings共享@flight-workspace/shared/util-auth认证库时,启动应用触发以下错误:
ENOENT: no such file or directory, scandir 'C:\Users\stefa\Local_Storage\advanced-nx-workspace\node_modules@flight-workspace\shared\util-auth'
Webpack未读取tsconfig中的路径映射,反而去node_modules目录查找目标库。相关Webpack配置如下:
const ModuleFederationPlugin = require('webpack/lib/container/ModuleFederationPlugin'); const mf = require('@angular-architects/module-federation/webpack'); const path = require('path'); const share = mf.share; const sharedMappings = new mf.SharedMappings(); sharedMappings.register(path.join(__dirname, '../../tsconfig.base.json'), [ '@flight-workspace/shared/util-auth', ]); module.exports = { output: { uniqueName: 'passenger', publicPath: 'auto', }, optimization: { runtimeChunk: false, }, resolve: { alias: { ...sharedMappings.getAliases(), }, }, experiments: { outputModule: true, }, plugins: [ new ModuleFederationPlugin({ library: { type: 'module' }, // For remotes (please adjust) name: 'passenger', filename: 'remoteEntry.js', // <-- Metadata generated by webpack exposes: { './Module': './apps/passenger/src/app/passenger/passenger.module.ts', }, shared: share({ '@angular/core': { singleton: true, strictVersion: true, requiredVersion: 'auto', }, '@angular/common': { singleton: true, strictVersion: true, requiredVersion: 'auto', }, '@angular/common/http': { singleton: true, strictVersion: true, requiredVersion: 'auto', }, '@angular/router': { singleton: true, strictVersion: true, requiredVersion: 'auto', }, ...sharedMappings.getDescriptors(), }), }), sharedMappings.getPlugin(), ], };
解决方案
1. 校验tsconfig路径映射正确性
打开项目根目录的tsconfig.base.json,确认paths字段中@flight-workspace/shared/util-auth的映射路径与实际文件位置一致:
"compilerOptions": { // ...其他配置 "paths": { "@flight-workspace/shared/util-auth": ["libs/shared/util-auth/src/index.ts"] } }
确保路径指向库的入口文件(通常是index.ts),避免相对路径层级错误。
2. 强制SharedMappings优先本地路径
在注册SharedMappings时添加forceUnshared选项,强制Webpack使用本地库而非去node_modules查找:
const sharedMappings = new mf.SharedMappings(); sharedMappings.register( path.join(__dirname, '../../tsconfig.base.json'), ['@flight-workspace/shared/util-auth'], { forceUnshared: true } );
3. 手动补充Webpack别名映射
如果自动生成的别名不生效,直接在resolve.alias中手动指定库的物理路径:
resolve: { alias: { ...sharedMappings.getAliases(), '@flight-workspace/shared/util-auth': path.resolve(__dirname, '../../libs/shared/util-auth/src/index.ts') }, },
4. 清理缓存并重建
Webpack缓存可能残留旧路径配置,执行以下操作清理后重启:
- 若使用NX项目:
npx nx reset - 通用方式:删除
node_modules/.cache、dist目录,再重新执行构建命令
5. 验证别名生成结果
在Webpack配置中打印别名信息,确认映射是否正确:
console.log('Shared Mappings Aliases:', sharedMappings.getAliases());
启动时查看控制台输出,确保@flight-workspace/shared/util-auth指向本地库的正确路径。
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

