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

Angular13项目基于angular-devkit集成module-federation实现微前端的方案咨询

Angular 13 微前端(Module Federation)兼容原生angular-devkit构建方案

核心思路:直接扩展angular-devkit的webpack配置

Angular 13的angular-devkit底层基于Webpack 5,而Module Federation是Webpack 5原生特性,完全不需要依赖ngx-build-plus。你可以通过自定义Webpack配置的方式,在保留原有构建流程的前提下集成Module Federation,具体步骤如下:


1. 安装自定义Webpack构建器

安装@angular-builders/custom-webpack,它允许在原生angular-devkit构建流程中注入自定义Webpack配置:

npm install @angular-builders/custom-webpack --save-dev

2. 编写Module Federation配置文件

在项目根目录创建webpack.config.js,配置Module Federation核心参数(示例为远程应用配置,宿主应用可调整对应参数):

const { ModuleFederationPlugin } = require('webpack').container;

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      // 应用唯一标识
      name: 'remoteApp',
      // 远程入口文件名称
      filename: 'remoteEntry.js',
      // 暴露给宿主应用的模块路径
      exposes: {
        './UserModule': './src/app/user/user.module.ts',
        './HeaderComponent': './src/app/header/header.component.ts'
      },
      // 共享依赖配置,避免多实例冲突
      shared: {
        '@angular/core': { singleton: true, strictVersion: true },
        '@angular/common': { singleton: true, strictVersion: true },
        '@angular/router': { singleton: true, strictVersion: true },
        'rxjs': { singleton: true, strictVersion: true }
      }
    })
  ]
};

3. 修改angular.json切换构建器

将项目的build和serve指令的构建器替换为自定义Webpack版本,并指定配置文件路径:

"architect": {
  "build": {
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./webpack.config.js"
      },
      // 保留原有build配置(outputPath、index、main等)
    }
  },
  "serve": {
    "builder": "@angular-builders/custom-webpack:dev-server",
    // 保留原有serve配置(port、open等)
  }
}

关键注意事项

  • 版本兼容性检查:执行npm ls webpack确认项目Webpack版本为5.x(Angular 13默认适配Webpack 5.64.x左右),避免版本冲突
  • 共享依赖验证:shared配置中严格启用singleton和strictVersion,确保跨应用的Angular核心依赖只有一个实例
  • 现有插件兼容:项目中原有的Webpack插件(如压缩、资源处理插件)可直接添加到webpack.config.js的plugins数组中,不影响原有构建逻辑

执行ng build或ng serve后,检查输出目录是否生成remoteEntry.js,即可验证配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 11:15:37