微前端 - Native Federation使用完整示例

       这是一个极简化的 Angular 使用@angular-architects/native-federation 插件的微前端示例,只包含一个主应用和一个远程应用。

完整示例展示

项目结构

federation-simple/
├── host-app/      # 主应用
└── remote-app/    # 远程应用

创建远程应用 (remote-app)

 初始化项目
ng new remote-app --standalone --minimal --style=css --routing=false
cd remote-app
npm install @angular-architects/native-federation --save-dev
配置 Native Federation
ng add @angular-architects/native-federation --project remote-app --port 4201
创建远程组件

编辑 src/app/hello.component.ts:

import { Component } from '@angular/core';@Component({standalone: true,template: `<div style="border: 2px solid blue;padding: 20px;margin: 10px;border-radius: 5px;"><h2>Hello from Remote App!</h2><p>This component is loaded from the remote app</p></div>`
})
export class HelloComponent {}
配置暴露的模块

编辑 federation.config.js:

module.exports = {name: 'remoteApp',exposes: {'./Hello': './src/app/hello.component.ts'},shared: {'@angular/core': { singleton: true, strictVersion: true },'@angular/common': { singleton: true, strictVersion: true },'rxjs': { singleton: true, strictVersion: true }}
};

创建主应用 (host-app)

初始化项目
ng new host-app --standalone --minimal --style=css --routing=true
cd host-app
npm install @angular-architects/native-federation @angular-architects/module-federation-tools --save-dev
配置 Native Federation
ng add @angular-architects/native-federation --project host-app --port 4200
创建主页面

编辑 src/app/app.component.ts:

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';@Component({standalone: true,imports: [CommonModule, RouterOutlet],template: `<div style="padding: 20px;"><h1>Host Application</h1><nav><a routerLink="/" style="margin-right: 15px;">Home</a><a routerLink="/remote">Load Remote Component</a></nav><router-outlet></router-outlet></div>`
})
export class AppComponent {}
创建远程组件加载页面

创建 src/app/remote.component.ts:

在这里使用了<app-remote-hello> 那这个怎么来的呢?请见下面的关键点说明第四点!!!

import { Component, OnInit } from '@angular/core';
import { loadRemoteModule } from '@angular-architects/module-federation';@Component({standalone: true,template: `<div style="margin-top: 20px;"><h2>Remote Component</h2><div *ngIf="loading">Loading remote component...</div><div *ngIf="error" style="color: red;">Failed to load remote component: {{error}}</div><ng-container *ngIf="!loading && !error"><app-remote-hello></app-remote-hello></ng-container></div>`
})
export class RemoteComponent implements OnInit {loading = true;error: string | null = null;async ngOnInit() {try {await loadRemoteModule({remoteEntry: 'http://localhost:4201/remoteEntry.js',remoteName: 'remoteApp',exposedModule: './Hello'});this.loading = false;} catch (err) {this.error = err instanceof Error ? err.message : String(err);this.loading = false;}}
}
配置路由

编辑 src/app/app.routes.ts:

import { Routes } from '@angular/router';
import { RemoteComponent } from './remote.component';export const APP_ROUTES: Routes = [{ path: 'remote', component: RemoteComponent,providers: [// 注册远程组件{provide: 'remote-hello',useValue: {remoteEntry: 'http://localhost:4201/remoteEntry.js',remoteName: 'remoteApp',exposedModule: './Hello',componentName: 'Hello'}}]},{ path: '**', redirectTo: 'remote' }
];
配置应用

编辑 src/app/app.config.ts:

import { ApplicationConfig, importProvidersFrom } from '@angular/core';
import { provideRouter } from '@angular/router';
import { APP_ROUTES } from './app.routes';
import { RemoteComponent } from '@angular-architects/module-federation-tools';export const appConfig: ApplicationConfig = {providers: [provideRouter(APP_ROUTES),importProvidersFrom(RemoteComponent.forRemote({type: 'module',remoteEntry: 'http://localhost:4201/remoteEntry.js',exposedModule: './Hello',componentName: 'Hello'}))]
};
配置 federation

编辑 federation.config.js: 

module.exports = {name: 'hostApp',remotes: {'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 },'rxjs': { singleton: true, strictVersion: true }}
};

运行应用

  1. 打开两个终端窗口
  2. 在第一个终端中运行远程应用
  3. 在第二个终端中运行主应用
  4. 访问应用
  5. 在主应用中,点击 "Load Remote Component" 链接将加载并显示远程组件

关键点说明

项目简单说明下面三点:

  1. 远程应用: remote中暴露一个了简单的HelloCompoent并且配置了共享的 Angular 核心库;

  2. 主应用: host中使用 了loadRemoteModule动态加载远程组件,同时通过路由导航到远程组件,并且配置了远程模块的引用;

  3. 共享依赖: remote项目和Host项目Angular 核心库和 RxJS 被标记为共享单例,并且确保了版本兼容性

  4. <app-remote-hello> 这个selector怎么来的

app-remote-hello 是自定义元素,通过下面的方式创建和使用的:

组件名称的生成规则: 当使用 @angular-architects/module-federation-tools 的 RemoteComponent时,组件名称会自动按照以下规则生成:

app-remote-<componentName>
  • app 是 Angular 默认的前缀
  • remote 表示这是一个远程组件
  • <componentName> 是你在配置中指定的组件名称(这里是 hello

具体配置来源:在示例中,这个名称来源于下面几个地方的配置:

在 app.config.ts 中:

importProvidersFrom(RemoteComponent.forRemote({type: 'module',remoteEntry: 'http://localhost:4201/remoteEntry.js',exposedModule: './Hello',componentName: 'Hello'  // ← 这里定义了基础名称})
)

在 remote.component.ts 中:

<app-remote-hello></app-remote-hello>

完整的名称转换过程:

  • 你配置了 componentName: Hello
  • 系统会自动转换为小写形式:hello
  • 加上前缀 app-remote- 形成最终标签名:app-remote-hello

如何自定义这个名称:如果想使用不同的标签名,可以这样修改

// 在 app.config.ts 中
RemoteComponent.forRemote({// ...其他配置componentName: 'MyCustomHello',  // 自定义名称elementName: 'my-hello-element'  // 自定义元素名(可选)
})// 然后在模板中使用
<my-hello-element></my-hello-element>

为什么能这样使用:这是因为 @angular-architects/module-federation-tools 在底层做了以下工作:

  • 动态注册了一个新的 Angular 组件

  • 将该组件定义为自定义元素(Custom Element)

  • 自动处理了组件名称的转换

  • 设置了与远程组件的连接

验证方法:如果你想确认这个组件是如何被注册的,可以在浏览器开发者工具中:

  • 打开 Elements 面板

  • 找到 <app-remote-hello> 元素

  • 查看它的属性,会发现它是一个 Angular组件

    • Angular 组件会有特殊属性

      • 查看是否有 _nghost-* 和 _ngcontent-* 这类 Angular 特有的属性

      • 例如:<app-remote-hello _ngcontent-abc="" _nghost-def="">

    • 检查自定义元素定义

      • 在 Console 中输入:document.querySelector('app-remote-hello').constructor.name

      • 如果是 Angular 组件,通常会显示 HTMLElement(因为 Angular 组件最终是自定义元素)

 参考资料:

核心资源

  1. @angular-architects/native-federation 官方文档
    📖 GitHub 仓库 & 文档

    • 包含安装指南、配置选项和基本用法

  2. Module Federation 概念解释
    📖 Webpack 官方文档

    • 理解微前端的核心机制


教程文章

  1. Angular 微前端完整指南
    📖 Angular Architects 博客

    • 含代码示例和架构图

  2. 实战案例分步教程
    📖 Dev.to 详细教程

    • 从零开始的实现步骤


视频资源

  1. 官方演示视频
    ▶️ YouTube 教程

    • 30分钟实战演示(Angular团队录制)

  2. 模块联邦深度解析
    ▶️ Webpack 官方频道

    • 底层原理讲解


扩展工具

  1. 模块联邦工具库
    📦 npm @angular-architects/module-federation-tools
    • 简化动态加载的工具

  2. 微前端状态管理方案
    📖 NgRx 集成指南
    • 跨应用状态管理建议


常见问题

  1. 共享依赖解决方案
    ❓ Stack Overflow 热门讨论

    • 版本冲突处理方案

  2. 生产环境部署指南
    📖 Angular 部署文档

    • 包含微前端部署注意事项


示例代码库

  1. 官方示例项目:可直接运行的完整项目
    💻 GitHub 代码库

    本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.pswp.cn/web/83282.shtml

    如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

    相关文章

    无服务器架构的企业级应用深度解析:Serverless技术选型与成本模型

    📋 目录 引言:无服务器架构的兴起无服务器架构核心概念主流Serverless平台技术对比企业级应用场景分析成本模型深度分析私有化部署与云端服务对比决策框架构建最佳实践与建议未来发展趋势结论引言:无服务器架构的兴起 在云计算快速发展的今天,无服务器架构(Serverless)…

    内网有猫和无线路由器,如何做端口映射从而实现外网访问

    内网猫和无线路由器端口映射配置指南 端口映射&#xff08;Port Forwarding&#xff09;是将外网请求引导到内网特定设备和端口的技术&#xff0c;常用于远程访问、搭建服务器等场景。以下是配置方法&#xff1a; 基本原理 猫&#xff08;调制解调器&#xff09;&#xff1a…

    Spring boot应用监控集成

    Spring Boot应用监控集成记录 背景 XScholar文献下载应用基于Spring Boot构建&#xff0c;需要接入Prometheus监控系统。应用已部署并运行在服务器上&#xff0c;需要暴露metrics端点供Prometheus采集。 初始状态 应用信息 框架: Spring Boot 2.x部署端口: 10089服务器: L…

    安宝特案例丨又一落地,Vuzix AR眼镜助力亚马逊英国仓库智能化升级!

    Vuzix M400智能眼镜近日落地亚马逊&#xff08;英国&#xff09;仓库&#xff0c;通过解放双手、免提操作优化物流效率。 安宝特&VuzixAR智能眼镜解决方案为亚马逊仓库提供实时决策支持、无缝对接员工-主管-企业管理系统&#xff0c;并加速了新员工培训流程&#xff0c;优…

    ui框架-文件列表展示

    ui框架-文件列表展示 介绍 UI框架的文件列表展示组件&#xff0c;可以展示文件夹&#xff0c;支持列表展示和图标展示模式。组件提供了丰富的功能和可配置选项&#xff0c;适用于文件管理、文件上传等场景。 功能特性 支持列表模式和网格模式的切换展示支持文件和文件夹的层…

    使用QMediaPlayer开发音乐播放器

    编译完成的程序下载:【免费】使用QMediaPlayer开发音乐播放器资源-CSDN文库 完整源码:使用QMediaPlayer开发音乐播放器源码资源-CSDN文库 需求分析: 1.本地音乐播放器 核心播放功能 支持常见音频格式本地播放MP3、WAV、FLAC 等 2.播放控制:播放 / 暂停 / 停止 / 上一曲…

    Linux-07 ubuntu 的 chrome 启动不了

    文章目录 问题原因解决步骤一、卸载旧版chrome二、重新安装chorme三、启动不了&#xff0c;报错如下四、启动不了&#xff0c;解决如下 总结 问题原因 在应用中可以看到chrome&#xff0c;但是打不开(说明&#xff1a;原来的ubuntu系统出问题了&#xff0c;这个是备用的硬盘&a…

    【Redis】缓存雪崩、缓存击穿、缓存穿透

    目录 1、缓存雪崩【1】定义【2】原因【3】解决方案[1]差异化过期时间[2]多级缓存[3]熔断降级[4]缓存永不过期异步更新 2、缓存击穿【1】定义【2】原因【3】解决方案[1]互斥锁[2]逻辑过期[3]热点数据加载 3、缓存穿透【1】定义【2】原因【3】解决方案[1]缓存空对象[2]布隆过滤器…

    【论文阅读笔记】万花筒:用于异构多智能体强化学习的可学习掩码

    摘要 在多智能体强化学习&#xff08;MARL&#xff09;中&#xff0c;通常采用参数共享来提高样本效率。然而&#xff0c;全参数共享的流行方法通常会导致智能体之间的策略同质&#xff0c;这可能会限制从策略多样性中获得的性能优势。为了解决这一关键限制&#xff0c;我们提出…

    vue2 , el-select 多选树结构,可重名

    人家antd都支持&#xff0c;elementplus 也支持&#xff0c;vue2的没有&#xff0c;很烦。 网上其实可以搜到各种的&#xff0c;不过大部分不支持重名&#xff0c;在删除的时候可能会删错&#xff0c;比如树结构1F的1楼啊&#xff0c;2F的1楼啊这种同时勾选的情况。。 可以全…

    golang循环变量捕获问题​​

    在 Go 语言中&#xff0c;当在循环中启动协程&#xff08;goroutine&#xff09;时&#xff0c;如果在协程闭包中直接引用循环变量&#xff0c;可能会遇到一个常见的陷阱 - ​​循环变量捕获问题​​。让我详细解释一下&#xff1a; 问题背景 看这个代码片段&#xff1a; fo…

    【一文看懂Spring循环依赖】Spring循环依赖:从陷阱破局到架构涅槃

    &#x1f32a;️ Spring Boot循环依赖&#xff1a;从陷阱破局到架构涅槃 循环依赖如同莫比乌斯环上的蚂蚁&#xff0c;看似前进却永远困在闭环中。本文将带你拆解Spring中这一经典难题&#xff0c;从临时救火到根治重构&#xff0c;构建无懈可击的依赖体系。 &#x1f525; 一、…

    el-table封装自动滚动表格(适用大屏)

    表格功能&#xff1a;自动滚动&#xff0c;鼠标移入停止滚动&#xff0c;移出继续滚动。如果想加触底加载新数据可以判断 scrollWrap.scrollTop和maxScrollTop大小来加载数据&#xff0c;另写逻辑。 <template><el-table ref"eltable" :data"tableDa…

    Eureka REST 相关接口

    可供非 Java 应用程序使用的 Eureka REST 操作。 appID 是应用程序的名称&#xff0c;instanceID 是与实例关联的唯一标识符。在 AWS 云中&#xff0c;instanceID 是实例的实例 ID&#xff1b;在其他数据中心&#xff0c;它是实例的主机名。 对于 XML/JSON&#xff0c;HTTP 的…

    DSP——时钟树讲解

    配置任何外设的第一步都要看一下时钟树,下图是DSP28377的时钟树: 由图所示DSP28377由4个时钟源,分别是INTOSC1、INTOSC2、XTAL、AUXCL INTOSC1:0M内部系统时钟,备用时钟,检测到系统时钟缺失自动连接到备用时钟,也作为看门狗时钟使用; INTOSC2:10M内部系统时钟,复位…

    少量数据达到更好效果

    九坤团队新作&#xff01;一条数据训练AI超越上万条数据 一 仅需一条无标签数据和10步优化 九坤团队训练了13,440个大模型&#xff0c;发现熵最小化 (EM) 仅需一条无标签数据和10步优化&#xff0c;就能实现与强化学习中使用成千上万条数据和精心设计的奖励机制所取得的性能提…

    html - <mark>标签

    <mark> 标签在HTML中用于高亮显示文本&#xff0c;通常用于突出显示某些重要的部分。它的默认样式通常是背景色为黄色&#xff0c;但你可以通过CSS自定义其外观。 1. 基本用法 <mark> 标签用于标记文本的高亮显示。它常用于搜索结果中&#xff0c;突出显示匹配的…

    YOLOv8+ByteTrack:高精度人车过线统计系统搭建指南

    文章目录 1. 引言2. YOLOv8简介3. 过线统计原理4. 代码实现4.1 环境准备4.2 基础检测代码4.3 过线统计实现4.4 完整代码示例5. 性能优化与改进5.1 多线程处理5.2 区域检测优化5.3 使用ByteTrack改进跟踪6. 实际应用中的挑战与解决方案7. 总结与展望1. 引言 目标检测是计算机视…

    20、React常用API和Hook索引

    这一小节中只给出一些API和Hook的索引&#xff0c;需要用到的时候可以去官网查询&#xff0c;如无必要此处不列出详细用法。React v1.19.1。 对Components的支持 以下是开发时通用的一些功能组件 APIdescription<Fragment>通常使用 <>…</> 代替&#xff0…

    Python爬虫实战:研究feedparser库相关技术

    1. 引言 1.1 研究背景与意义 在当今信息爆炸的时代,互联网上存在着海量的信息资源。RSS(Really Simple Syndication)作为一种标准化的信息聚合技术,被广泛用于网站内容的发布和订阅。通过 RSS,用户可以方便地获取网站更新的内容,而无需频繁访问各个网站。 然而,互联网…