Angular微前端架构:Module Federation + ngx-build-plus (Webpack)

以下是一个完整的 Angular 微前端示例,其中使用的是 Module Federation 和 npx-build-plus 实现了主应用(Shell)与子应用(Remote)的集成。

🛠️ 项目结构

复制代码
angular-mf/
├── shell-app/       # 主应用(Shell)
├── remote-app/      # 子应用(Remote)
├── angular.json     # Angular CLI 配置
└── package.json     # 项目依赖

1️⃣ 安装依赖

首先,确保你已安装 npx-build-plus:

复制代码
ng add ngx-build-plus

然后,安装 @angular-architects/module-federation:

复制代码
npm install @angular-architects/module-federation --save-dev

2️⃣ 配置 Remote 应用(子应用)

在remote-app/webpack.config.js 中,配置ModuleFederationPlugin:

复制代码
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  output: {
    uniqueName: 'remoteApp',
    publicPath: 'auto',
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'remoteApp',
      filename: 'remoteEntry.js',
      exposes: {
        './RemoteModule': './src/app/remote/remote.module.ts',
      },
      shared: {
        '@angular/core': { singleton: true, strictVersion: true },
        '@angular/common': { singleton: true, strictVersion: true },
        '@angular/router': { singleton: true, strictVersion: true },
      },
    }),
  ],
};

3️⃣ 配置 Shell 应用(主应用)

在 shell-app/webpack.config.js 中,配置ModuleFederationPlugin:

复制代码
const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  output: {
    uniqueName: 'shellApp',
  },
  plugins: [
    new ModuleFederationPlugin({
      name: 'shellApp',
      remotes: {
        remoteApp: 'remoteApp@http://localhost:4201/remoteEntry.js',
      },
      shared: {
        '@angular/core': { singleton: true, strictVersion: true },
        '@angular/common': { singleton: true, strictVersion: true },
        '@angular/router': { singleton: true, strictVersion: true },
      },
    }),
  ],
};

4️⃣ 配置 Angular.json File + Angular 路由

angular.json文件配置如下:angular.json 配置的关键部分是如何集成 npx-build-plus 以支持 Webpack Module Federation。

angular.json 配置说明

🧭 关键修改目标

  1. 使用 npx-build-plus 替代默认@angular-devkit/build-angular:browser

  2. 添加extraWebpackConfig 指向自定义的 Webpack 配置文件

  3. 配置输出格式(如 umdModules(非必须)、outputPath)

📁 angular.json 配置片段

复制代码
{
  "projects": {
    "shell-app": {
      "architect": {
        "build": {
          "builder": "ngx-build-plus:browser",
          "options": {
            "outputPath": "dist/shell-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.scss"],
            "scripts": [],
            "extraWebpackConfig": "webpack.config.js",
            "umdModuleIds": {
              "@angular/core": "ng.core",
              "@angular/common": "ng.common",
              "@angular/router": "ng.router"
            }
          },
          "configurations": {
            "production": {
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "ngx-build-plus:dev-server",
          "options": {
            "browserTarget": "shell-app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "shell-app:build:production"
            }
          }
        }
      }
    }
  }
}

📦 额外建议

  • 确保webpack.config.js 文件存在于根目录或指定位置。

  • 如果你有多个环境配置(如 staging/test),也可以扩展configurations 。

  • 如果你使用webpack.prod.config.js,可以在生产配置中加上extraWebpackConfig 覆盖。

在shell-app/src/app/app-routes.ts 中,配置动态加载 Remote 模块:

复制代码
import { Routes } from '@angular/router';
import { loadRemoteModule } from '@angular-architects/module-federation';

export const routes: Routes = [
  {
    path: 'remote',
    loadChildren: () =>
      loadRemoteModule({
        remoteName: 'remoteApp',
        exposedModule: './RemoteModule',
      }).then((m) => m.RemoteModule),
  },
];

5️⃣ 启动应用

分别启动 Remote 和 Shell 应用:

复制代码
# 启动 Remote 应用
cd remote-app
ng serve --port 4201

# 启动 Shell 应用
cd shell-app
ng serve --port 4200

访问 http://localhost:4200/remote 即可加载 Remote 模块。


✅ 总结

  • 使用 Webpack 5 的 ModuleFederationPlugin 实现了主应用与子应用的动态模块共享。

  • 通过npx-build-plus扩展了 Angular CLI 的构建功能,支持自定义 Webpack 配置。

  • 采用@angular-architects/module-federation提供的 loadRemoteModule实现了 Angular 路由的懒加载远程模块。

相关推荐
辻戋2 小时前
从零实现React Scheduler调度器
前端·react.js·前端框架
徐同保2 小时前
使用yarn@4.6.0装包,项目是react+vite搭建的,项目无法启动,报错:
前端·react.js·前端框架
Qrun3 小时前
Windows11安装nvm管理node多版本
前端·vscode·react.js·ajax·npm·html5
中国lanwp3 小时前
全局 npm config 与多环境配置
前端·npm·node.js
JELEE.4 小时前
Django登录注册完整代码(图片、邮箱验证、加密)
前端·javascript·后端·python·django·bootstrap·jquery
TeleostNaCl6 小时前
解决 Chrome 无法访问网页但无痕模式下可以访问该网页 的问题
前端·网络·chrome·windows·经验分享
前端大卫7 小时前
为什么 React 中的 key 不能用索引?
前端
你的人类朋友7 小时前
【Node】手动归还主线程控制权:解决 Node.js 阻塞的一个思路
前端·后端·node.js
小李小李不讲道理9 小时前
「Ant Design 组件库探索」五:Tabs组件
前端·react.js·ant design
毕设十刻9 小时前
基于Vue的学分预警系统98k51(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js