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

news2025/6/9 20:44:03

       这是一个极简化的 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.coloradmin.cn/o/2405818.html

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

    相关文章

    自然语言处理——语言模型

    语言模型 n元文法参数估计数据平滑方法加1法 神经网络模型提出原因前馈神经网络&#xff08;FNN&#xff09;循环神经网络 n元文法 大规模语料库的出现为自然语言统计处理方法的实现提供了可能&#xff0c;统计方法的成功应用推动了语料库语言学的发展。 语句 &#x1d460; …

    数据库管理与高可用-MySQL高可用

    目录 #1.1什么是MySQL高可用 1.1.1MySQL主主复制keepalivedhaproxy的高可用 1.1.2优势 #2.1MySQL主主复制keepalivedhaproxy的实验案例 1.1什么是MySQL高可用 MySQL 高可用是指通过技术手段确保 MySQL 数据库在面临硬件故障、软件错误、网络中断、人为误操作等异常情况时&…

    免费工具-微软Bing Video Creator

    目录 引言 一、揭秘Bing Video Creator 二、轻松上手&#xff1a;三步玩转Bing Video Creator 2.1 获取与访问&#xff1a; 2.2 创作流程&#xff1a; 2.3 提示词撰写技巧——释放AI的想象力&#xff1a; 三、核心特性详解&#xff1a;灵活满足多样化需求 3.1 双重使用模…

    【笔记】解决MSYS2安装后cargo-install-update.exe-System Error

    #工作记录 cargo-install-update.exe-System Error The code execution cannot proceed because libgit2-1.9.dll wasnot found. Reinstalling the program may fix this problem. …

    银行卡二三四要素实名接口如何用PHP实现调用?

    一、什么是银行卡二三四要素实名接口 输入银行卡卡号、姓名、身份证号码、手机号&#xff0c;验证此二三四要素是否一致。 二、核心价值 1. 提升风控效率 通过实时拦截冒用身份开户&#xff0c;银行卡二三四要素实名接口显著降低了人工审核成本&#xff0c;效率提升50%以上…

    itvbox绿豆影视tvbox手机版影视APP源码分享搭建教程

    我们先来看看今天的主题&#xff0c;tvbox手机版&#xff0c;然后再看看如何搭建&#xff1a; 很多爱好者都希望搭建自己的影视平台&#xff0c;那该如何搭建呢&#xff1f; 后端开发环境&#xff1a; 1.易如意后台管理优化版源码&#xff1b; 2.宝塔面板&#xff1b; 3.ph…

    网页抓取混淆与嵌套数据处理流程

    当我们在网页抓取中&#xff0c;遇到混淆和多层嵌套的情况是比较常见的挑战。混淆大部分都是为了防止爬虫而设计的&#xff0c;例如使用JavaScript动态加载、数据加密、字符替换、CSS偏移等。多层嵌套则可能是指HTML结构复杂&#xff0c;数据隐藏在多层标签或者多个iframe中。 …

    高性能MYSQL:复制同步的问题和解决方案

    一、复制的问题和解决方案 中断MySQL的复制并不是件难事。因为实现简单&#xff0c;配置相当容易&#xff0c;但也意味着有很多方式会导致复制停止&#xff0c;陷入混乱并中断。 &#xff08;一&#xff09;数据损坏或丢失的错误 由于各种各样的原因&#xff0c;MySQL 的复制…

    大话软工笔记—架构模型

    1. 架构模型1—拓扑图 &#xff08;1&#xff09;拓扑图概念 拓扑图&#xff0c;将多个软件系统用网络图连接起来的表达方式。 &#xff08;2&#xff09;拓扑图分类 总线型结构 比较普遍采用的方式&#xff0c;将所有的系统接到一条总线上。 星状结构 各个系统通过点到…

    javaweb -html -CSS

    HTML是一种超文本标记语言 超文本&#xff1a;超过了文本的限制&#xff0c;比普通文本更强大&#xff0c;除了文字信息&#xff0c;还可以定义图片、音频、视频等内容。 标记语言&#xff1a;由标签"<标签名>"构成的语言。 CSS:层叠样式表&#xff0c;用于…

    spring task定时任务快速入门

    spring task它基于注解和配置&#xff0c;可以轻松实现任务的周期性调度、延迟执行或固定频率触发。按照我们约定的时间自动执行某段代码。例如闹钟 使用场景 每月还款提醒&#xff0c;未支付的订单自动过期&#xff0c;收到快递后自动收货&#xff0c;系统自动祝你生日快乐等…

    搭建nginx的负载均衡

    1、编写一个configMap的配置文件 events {worker_connections 1024; # 定义每个worker进程的最大连接数 }http {# 定义通用代理参数&#xff08;替代proxy_params文件&#xff09;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-F…

    Appium+python自动化(八)- 认识Appium- 下章

    1、界面认识 在之前安装appium的时候说过我们有两种方法安装&#xff0c;也就有两种结果&#xff0c;一种是有界面的&#xff08;客户端安装&#xff09;&#xff0c;一种是没有界面的&#xff08;终端安装&#xff09;&#xff0c;首先我们先讲一下有界面的&#xff0c;以及界…

    LabVIEW的MathScript Node 绘图功能

    该VI 借助 LabVIEW 的 MathScript Node&#xff0c;结合事件监听机制&#xff0c;实现基于 MathScript 的绘图功能&#xff0c;并支持通过交互控件自定义绘图属性。利用 MathScript 编写脚本完成图形初始化&#xff0c;再通过LabVIEW 事件结构响应用户操作&#xff0c;动态修改…

    每日Prompt:治愈动漫插画

    提示词 现代都市治愈动漫插画风格&#xff0c;现代女子&#xff0c;漂亮&#xff0c;长直发&#xff0c;20岁&#xff0c;豆沙唇&#xff0c;白皙&#xff0c;气质&#xff0c;清纯现代都市背景下&#xff0c;夕阳西下&#xff0c;一位穿着白色露脐短袖&#xff0c;粉色工装裤…

    6.8 note

    paxos算法_初步感知 Paxos算法保证一致性主要通过以下几个关键步骤和机制&#xff1a; 准备阶段 - 提议者向所有接受者发送准备请求&#xff0c;请求中包含一个唯一的编号。 - 接受者收到请求后&#xff0c;会检查编号&#xff0c;如果编号比它之前见过的都大&#xff0c;就会承…

    面试心得 --- 车载诊断测试常见的一些面试问题

    我是穿拖鞋的汉子,魔都中坚持长期主义的汽车电子工程师。 老规矩,分享一段喜欢的文字,避免自己成为高知识低文化的工程师: 做到欲望极简,了解自己的真实欲望,不受外在潮流的影响,不盲从,不跟风。把自己的精力全部用在自己。一是去掉多余,凡事找规律,基础是诚信;二是…

    跟进一下目前最新的大数据技术

    搭建最新平台 40C64G服务器&#xff0c;搭建3节点kvm&#xff0c;8C12G。 apache-hive-4.0.1-bin apache-tez-0.10.4-bin flink-1.20.1 hadoop-3.4.1 hbase-2.6.2 jdk-11.0.276 jdk8u452-b09 jdk8终于可以不用了 spark-3.5.5-bin-hadoop3 zookeeper-3.9.3 trino…

    系统模块与功能设计框架

    系统模块与功能设计框架&#xff0c;严格遵循专业架构设计原则&#xff0c;基于行业标准&#xff08;如微服务架构、DDD领域驱动设计&#xff09;构建。设计采用分层解耦模式&#xff0c;确保可扩展性和可维护性&#xff0c;适用于电商、企业服务、数字平台等中大型系统。 系统…

    我爱学算法之—— 前缀和(中)

    一、724. 寻找数组的中心下标 题目解析 这道题&#xff0c;给定数组nums&#xff0c;要求我们找出这个数组的中心下标。 **中心下标&#xff1a;**指左侧所有元素的和等于右侧所有元素的和。 如果存在多个中心数组下标&#xff0c;就返回最左侧的中心数组下标。 算法思路 暴…