You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Native Federation serve命令无法触发应用热重载

NX Monorepo Native Federation 下Lib模块修改无热重载问题

问题概述

在基于NX Monorepo、DDD架构的Native Federation POC项目中,mfe1应用依赖仓库内的domain和feature-content模块(依赖已在tsconfig.base.json中配置)。在mfe1/app.component.ts中引入并使用feature-content的ContentComponent后,修改feature-content模块内的文件(如libs/mfe1/feature-content/src/lib/content.component.html)时,构建流程会执行但热重载未触发,需手动刷新页面才能看到变更效果。但使用npx nx run mfe1:serve-original --configuration=development启动应用时,热重载功能完全正常。

复现步骤

  • 安装项目依赖:npm i
  • 通过Native Federation启动mfe1:npx nx run mfe1:serve
  • 修改libs/mfe1/feature-content/src/lib/content.component.html的内容,观察应用是否触发热重载

可能原因

  1. Native Federation监听范围未覆盖依赖Lib:默认的Native Federation serve任务可能未将feature-content模块纳入文件监听范围,导致模块文件变更后无法触发应用热重载。
  2. 模块缓存机制干扰:Native Federation对依赖模块启用了缓存,即使文件已变更,构建后的模块也未被重新注入到运行中的应用。
  3. NX项目依赖关联缺失:虽然tsconfig.base.json中配置了模块依赖,但mfe1的project.json未正确声明对feature-content模块的依赖,导致NX的watch任务未关联该Lib的文件变更。

解决方案

1. 调整mfe1的project.json配置

确保serve任务监听依赖Lib的文件变更,并声明项目依赖:

  • 在project.json的targets.serve.options中添加additionalWatchPaths,指定feature-content模块的路径:
"serve": {
  "executor": "@nrwl/angular:module-federation-dev-server",
  "options": {
    "buildTarget": "mfe1:build",
    "port": 4200,
    "watch": true,
    "additionalWatchPaths": ["libs/mfe1/feature-content/**/*"]
  },
  "configurations": {
    "production": {
      "buildTarget": "mfe1:build:production"
    }
  }
}
  • 在project.json根节点添加implicitDependencies,关联feature-content模块:
"implicitDependencies": ["mfe1-feature-content"]

2. 禁用依赖模块的缓存

在mfe1的module-federation.config.js中,针对feature-content模块禁用缓存:

module.exports = {
  name: 'mfe1',
  exposes: {
    './Module': './apps/mfe1/src/app/remote-entry/entry.module.ts',
  },
  shared: {
    '@angular/core': { singleton: true, strictVersion: true, requiredVersion: 'auto' },
    '@angular/common': { singleton: true, strictVersion: true, requiredVersion: 'auto' },
    '@angular/router': { singleton: true, strictVersion: true, requiredVersion: 'auto' },
    '@your-project/mfe1/feature-content': { eager: true, singleton: false, cache: false }
  },
};

3. 验证NX依赖图谱

运行nx dep-graph查看mfe1与feature-content的依赖关系是否正确,确保NX能识别两者的关联,这样watch任务会自动监听依赖模块的文件变更。

4. 升级NX到最新稳定版

如果当前使用的NX版本存在Native Federation热重载的已知bug,执行以下命令升级:

npx nx migrate latest
npm install
npx nx migrate --run-migrations

内容的提问来源于stack exchange,提问作者n_denny

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 05:41:27