在 Angular CLI 中,如何借助 @angular-architects/native-federation 避免 eject?
解读
面试官真正想确认的是:
- 你是否了解 Angular CLI 默认把 webpack 配置“黑盒化”,一旦 eject 就失去官方升级通道,国内很多团队因此长期卡在旧版本;
- 你是否知道 Module Federation 是 webpack 5 官方微前端方案,而 @angular-architects/native-federation 把它包装成 Angular 原生扩展,不 eject 也能改 webpack 配置;
- 你是否能落地:从安装、配置到生产部署,用 CLI 原生命令(ng serve / ng build)完成微前端拆分,同时保留后续无缝升级 Angular 的能力。
知识点
- Angular CLI 的 architect 钩子:@angular-devkit/architect 允许第三方 builder 在不 eject 的情况下替换默认 webpack 配置。
- @angular-architects/native-federation 的 builder 名称:
@angular-architects/native-federation:builder直接继承自@angular-devkit/build-angular:browser,只追加 federation 插件,其余逻辑完全复用官方链。 - federation 配置三大文件:
– federation.config.js(暴露模块、共享依赖、remotes 映射)
– tsconfig.federation.json(为 shell 和 remote 分别生成类型存根)
– angular.json 里把 defaultConfiguration 指向新 builder,ng 命令零变化。 - 共享依赖版本对齐:使用 sharedMappings 把 @angular/core、@angular/common、RxJS 等打入 single 版本,避免重复打包和运行时冲突。
- 国内部署注意:Nginx 需要给 remoteEntry.js 加 **Access-Control-Allow-Origin * **,否则跨域拉取失败;微前端包体大,建议 OSS + CDN 分片缓存。
答案
-
安装
ng add @angular-architects/native-federation
该 schematic 会自动:- 把 projects.*.architect.build.builder 替换成
@angular-architects/native-federation:builder - 在根目录生成 federation.config.js 与 tsconfig.federation.json
- 保持 angular.json 其余字段不动,CLI 官方升级通道完好。
- 把 projects.*.architect.build.builder 替换成
-
配置微前端
以“远程应用”为例,在 federation.config.js 中:const config = { name: 'mfeProducts', exposes: { './ProductModule': './src/app/product/product.module.ts', }, shared: share({ '@angular/core': { singleton: true, strictVersion: true, requiredVersion: 'auto' }, '@angular/common': { singleton: true, strictVersion: true, requiredVersion: 'auto' }, ...sharedMappings.getDescriptors(), }), }; module.exports = config; -
在 shell 应用里消费
const routes: Routes = [ { path: 'products', loadChildren: () => import('mfeProducts/ProductModule').then(m => m.ProductModule), }, ];import-map 由 native-federation 在运行时通过 remoteEntry.js 自动解析,无需手写 script 标签。
-
构建与运行
- 远程:
ng build mfeProducts --watch - Shell:
ng serve shell -o
全程使用 ng 原生命令,未执行 ng eject,webpack 配置由 builder 动态合并,升级 Angular 14→15→16 只需正常 ng update。
- 远程:
-
生产优化
- budgets 阈值在 angular.json 里继续生效,native-federation 不会关闭 CLI 的 bundle 告警。
- 开启 Nx 分布式缓存或 Angular CLI 的 cacheDir,CI 机器平均节省 40% 构建时间。
- 国内镜像源(淘宝、华为)需同步 @angular-architects 私有包,否则第一次 ng add 会超时。
拓展思考
- 对比 single-spa-angular:single-spa 需要改动 main.ts 和 zone.js 的引导方式,native-federation 完全保留 Angular 的 bootstrap 流程,对老代码侵入更小。
- 动态加载远程:结合 Angular Service + RxJS,可在运行时根据用户权限拉取不同的 remoteEntry.js,实现 “千人千面” 微前端。
- SSR 场景:Angular Universal 与 Module Federation 同时开启时,remote 必须在 Node 端预渲染完成,否则出现 window is not defined;官方给出的 @angular-architects/native-federation-ssr 已封装 ** Domino 模拟 DOM**,国内项目可直接套用。
- 未来演进:Angular 17 引入 esbuild + vite 实验链,@angular-architects 团队已发布 @angular-architects/native-federation-esbuild,配置层完全兼容,意味着今天用 webpack 5 写的 federation 明天可 零成本迁移到 esbuild,彻底避免二次 eject。
掌握这套思路,你不仅回答了“如何不 eject”,还向面试官展示了 对国内落地、性能、升级路径的深度把控,轻松拿到高分。