Angular 14中如何在组件内直接消费联邦化微前端代码
在Angular 14中直接使用Module Federation远程组件标签(无需路由加载)
前提确认
确保远程应用的MainPanelModule已导出MainPanelComponent,主应用导入该模块后才能识别组件选择器:
// 远程应用 src/main-panel/main-panel.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MainPanelComponent } from './main-panel.component'; @NgModule({ declarations: [MainPanelComponent], imports: [CommonModule], exports: [MainPanelComponent] // 必须导出组件 }) export class MainPanelModule { }
步骤1:保持现有Webpack配置不变
你当前的远程端和主应用Webpack配置已满足Module Federation的基础要求,无需额外修改。
步骤2:主应用异步加载远程模块并集成到根模块
修改主应用的main.ts,先异步加载远程模块,再合并到根模块中启动应用,确保Angular能识别远程组件的选择器:
// src/main.ts import { platformBrowserDynamic, NgModule } from '@angular/platform-browser-dynamic'; import { loadRemoteModule } from '@angular-architects/module-federation'; import { AppModule } from './app/app.module'; async function bootstrapApp() { // 加载远程模块 const remoteModule = await loadRemoteModule({ type: 'module', remoteEntry: 'http://localhost:4201/remoteEntry.js', exposedModule: './Module', }); // 创建合并模块,导入主应用模块和远程模块 const RootModule = NgModule({ imports: [AppModule, remoteModule.MainPanelModule] })(class MergedRootModule {}); // 启动应用 platformBrowserDynamic().bootstrapModule(RootModule) .catch(err => console.error('应用启动失败:', err)); } // 执行启动逻辑 bootstrapApp();
步骤3:直接在模板中使用组件标签
完成上述配置后,你可以在主应用任意组件的模板里直接使用<main-panel></main-panel>标签:
<!-- src/app/app.component.html --> <h1>主应用内容</h1> <main-panel></main-panel>
可选优化:延迟加载组件(避免阻塞应用启动)
如果不想在应用启动时就加载远程组件,可以在使用组件的地方动态触发加载:
// src/app/some-component.ts import { Component } from '@angular/core'; import { loadRemoteModule } from '@angular-architects/module-federation'; @Component({ selector: 'app-some', template: ` <button (click)="loadRemotePanel()">加载远程面板</button> <main-panel *ngIf="isPanelLoaded"></main-panel> ` }) export class SomeComponent { isPanelLoaded = false; async loadRemotePanel() { if (!this.isPanelLoaded) { await loadRemoteModule({ type: 'module', remoteEntry: 'http://localhost:4201/remoteEntry.js', exposedModule: './Module', }); this.isPanelLoaded = true; } } }
内容的提问来源于stack exchange,提问作者msmarkova
相关产品推荐
相关产品推荐

