Nx Monorepo中React宿主与Angular MFE的remoteEntry文件格式不匹配问题
React宿主加载Angular MFE时remoteEntry文件名不匹配的解决方法
问题核心
React宿主应用请求remoteEntry.js,但Angular MFE生成的是remoteEntry.mjs,导致404错误。以下两种方案可解决该问题:
方案1:修改React宿主的模块联邦配置,指定正确的remoteEntry路径
直接在React宿主(rxhost)的module-federation.config.js中,为Angular MFE明确指定.mjs后缀的entry文件:
// apps/rxhost/module-federation.config.js module.exports = { name: 'rxhost', remotes: [ 'react-mfe', { 'ng-mfe': 'ng-mfe@http://localhost:4202/remoteEntry.mjs' } ], // 保留其他原有配置 };
修改后重启宿主服务,即可正确请求Angular MFE的remoteEntry.mjs文件。
方案2:强制Angular MFE生成.js后缀的remoteEntry
由于Nx封装的Angular模块联邦默认生成.mjs文件,需通过自定义webpack配置覆盖默认设置:
- 在
apps/ng-mfe目录下创建webpack.config.js:
const { withModuleFederation } = require('@nrwl/angular/module-federation'); const moduleFederationConfig = require('./module-federation.config'); module.exports = withModuleFederation({ ...moduleFederationConfig, filename: 'remoteEntry.js' // 强制指定生成的文件名 });
- 修改
apps/ng-mfe/project.json,让build和serve目标使用自定义webpack配置:
{ "targets": { "build": { "executor": "@nrwl/angular:webpack-browser", "options": { "webpackConfig": "apps/ng-mfe/webpack.config.js", // 保留其他原有build配置 } }, "serve": { "executor": "@nrwl/angular:webpack-dev-server", "options": { "webpackConfig": "apps/ng-mfe/webpack.config.js", // 保留其他原有serve配置 } } } }
重新启动Angular MFE服务,此时会生成remoteEntry.js,与React宿主的请求路径匹配。
补充说明
- 直接修改Angular MFE的
module-federation.config.js中的filename属性无效,是因为Nx的withModuleFederation封装逻辑会覆盖该配置,必须通过自定义webpack配置传递。 - 两种方案任选其一即可,方案1无需修改Angular MFE的配置,更适合跨团队协作场景(Angular团队无需调整他们的构建配置)。
内容的提问来源于stack exchange,提问作者jmcnally
相关产品推荐
相关产品推荐

