Angular Module Federation 如何从Shell向MFE共享类、组件等非路由资源
Angular Module Federation 非路由资源加载解决方案
@angular-architects/module-federation 并不限制只能通过路由加载模块,完全支持运行时加载工具类、指令、独立组件、共享模块等任意非路由资源,无需依赖npm包发布流程即可实现代码共享。
1. 远程应用配置(暴露资源)
修改需要对外提供资源的远程微应用的webpack.config.js,在ModuleFederationPlugin的exposes字段中声明所有需要暴露的非路由资源即可,示例配置如下:
// 远程微应用 webpack.config.js 核心配置 const ModuleFederationPlugin = require("webpack/lib/container/ModuleFederationPlugin"); const shareAll = require("@angular-architects/module-federation/webpack").shareAll; module.exports = { plugins: [ new ModuleFederationPlugin({ name: "remoteApp", filename: "remoteEntry.js", exposes: { // 暴露普通工具类 './common-utils': './src/app/shared/utils/common.util.ts', // 暴露独立组件 './standalone-card': './src/app/shared/components/card/card.component.ts', // 暴露自定义指令 './highlight-directive': './src/app/shared/directives/highlight.directive.ts', // 暴露公共共享模块(可包含非独立组件、管道、通用服务等) './shared-module': './src/app/shared/shared.module.ts', }, shared: { ...shareAll({ singleton: true, strictVersion: true, requiredVersion: 'auto' }), }, }), ], };
2. 宿主/Shell应用加载资源
不需要绑定路由,可在应用任意位置(服务、组件、模块)通过loadRemoteModule方法动态加载远程暴露的资源,以下是常见场景的用法:
加载远程工具类
import { loadRemoteModule } from '@angular-architects/module-federation'; // 可在任意业务逻辑中调用 async function useRemoteUtils() { const utilsModule = await loadRemoteModule({ type: 'module', remoteEntry: 'http://<远程应用地址>/remoteEntry.js', exposedModule: './common-utils' }); // 直接调用远程工具方法 const formatResult = utilsModule.formatDate(new Date()); }
加载远程独立组件并渲染
import { ViewContainerRef } from '@angular/core'; import { loadRemoteModule } from '@angular-architects/module-federation'; async function loadRemoteCard(vcr: ViewContainerRef) { const cardModule = await loadRemoteModule({ type: 'module', remoteEntry: 'http://<远程应用地址>/remoteEntry.js', exposedModule: './standalone-card' }); // 动态创建组件实例并渲染到视图容器 const componentRef = vcr.createComponent(cardModule.CardComponent); // 传入组件输入参数 componentRef.instance.title = '远程加载的卡片组件'; }
加载远程共享模块
// 宿主应用的任意功能模块中导入远程共享模块 import { NgModule } from '@angular/core'; import { loadRemoteModule } from '@angular-architects/module-federation'; @NgModule({ imports: [ CommonModule, loadRemoteModule({ type: 'module', remoteEntry: 'http://<远程应用地址>/remoteEntry.js', exposedModule: './shared-module' }).then(m => m.SharedModule) ] }) export class LocalFeatureModule { }
导入后即可在当前模块的所有组件中,直接使用远程共享模块导出的非独立组件、指令、管道等资源,使用方式和本地导入的模块完全一致。
注意事项
- 需确保宿主和远程应用的公共依赖(如
@angular/core、@angular/common等)版本对齐,配置singleton: true避免重复加载 - 如果要使用远程非独立组件/指令,需要在远程应用的共享模块中将对应资源加入
exports数组 - TypeScript类型提示可通过手动编写
.d.ts声明文件,或使用模块联邦类型同步工具实现
内容的提问来源于stack exchange,提问作者iamaword
相关产品推荐
相关产品推荐

