react-manifest-example 宿主应用实战:基于 Module Federation 2.0 与 Rspack 的 React 微前端接入指南
react-manifest-example 宿主应用实战:基于 Module Federation 2.0 与 Rspack 的 React 微前端接入指南
本指南以 react-manifest-example 仓库中的 host 应用(react-manifest-example/host/README.md)为核心,系统讲解如何用 @module-federation/enhanced 的 Rspack 插件构建一个基于 Module Federation 2.0 的 React 宿主(Host)应用,并通过 mf-manifest.json 清单文件消费两个远程(Remote)应用。读完本文,你将掌握 host 端 rsbuild.config.ts 的完整配置含义、静态 import 与动态 loadRemote 两种消费远程组件的写法、@mf-types 自动类型生成的接入方式,以及 dev / build / preview 三种运行态的区别与端口规划。
一、示例整体架构:一个 Host 与两个 Remote
整个 react-manifest-example 是一个以 Rspack 为构建引擎、使用 Module Federation 2.0(@module-federation/enhanced 2.0.1)搭建的 React 微前端演示,包含三个应用:
| 应用 | 目录 | 端口 | 角色 |
|---|---|---|---|
| host | react-manifest-example/host | 3000 | 宿主,路由容器,负责加载远程组件 |
| remote1 | react-manifest-example/remote1 | 3001 | 远程应用一,暴露 ./button、./app |
| remote2 | react-manifest-example/remote2 | 3002 | 远程应用二,暴露 ./button |
三个应用均为独立 pnpm workspace 包(react-manifest-example_host、react-manifest-example_remote1、react-manifest-example_remote2),因此根目录 react-manifest-example/package.json 中的 start 脚本用 pnpm run --filter react-manifest-example_** --parallel dev 并行启动全部应用:
pnpm run --filter react-manifest-example_** --parallel dev
host 运行时位于 http://localhost:3000(仅 live reload);remote1、remote2 支持 HMR(分别位于 3001、3002 端口)。这一端口分工正是宿主应用稳定复用远程热更新能力的关键:远程应用独立热更新,宿主只需在清单文件(manifest)层面感知其最新产物。
二、安装与运行:host 的标准开发流程
原文档 react-manifest-example/host/README.md 给出了 Rsbuild 项目标准的四步流程,在 monorepo 中可以直接在仓库根目录统一执行:
1. 安装依赖
pnpm install
host 的关键依赖在 react-manifest-example/host/package.json 中:
@module-federation/enhanced:2.0.1,提供ModuleFederationPlugin与运行时loadRemote;@rsbuild/core1.7.3 与@rsbuild/plugin-react1.4.5:构建与 React 支持;react/react-dom18.3.1:共享依赖版本;react-router-dom6.30.2:宿主路由;antd与@ant-design/icons:宿主页面的 UI 组件。
2. 启动开发服务器
pnpm dev
对应脚本为 rsbuild dev --open(host/package.json),--open 会在启动后自动打开浏览器;host 自身监听 3000 端口(见下文配置)。在 monorepo 根目录下也可以直接运行 pnpm start 一次并行拉起三个应用。
3. 生产构建
pnpm build
对应脚本为 rsbuild build,会为 host 生成生产产物;远程应用则会在构建阶段产出对应的 mf-manifest.json 清单文件供宿主引用。
4. 本地预览生产产物
pnpm preview
对应脚本为 rsbuild preview,用于在本地验证 build 产物的实际效果。
提示:若在根目录执行,需先
cd react-manifest-example再运行pnpm install && pnpm run start(根 README 强调无需在子目录重复安装,由 workspace 统一管理依赖)。
三、host 端 Module Federation 2.0 配置逐项解析
host 的构建配置集中在 react-manifest-example/host/rsbuild.config.ts,这是理解整个示例的关键文件:
import { defineConfig } from '@rsbuild/core';
import { pluginReact } from '@rsbuild/plugin-react';
import { ModuleFederationPlugin } from '@module-federation/enhanced/rspack';
export default defineConfig({
server: {
port: 3000,
},
tools: {
rspack: (config, { appendPlugins }) => {
appendPlugins([
new ModuleFederationPlugin({
name: 'host',
shareStrategy: 'loaded-first',
experiments: { asyncStartup: true },
remotes: {
remote1: 'remote1@http://localhost:3001/mf-manifest.json',
remote2: 'remote2@http://localhost:3002/mf-manifest.json',
},
shared: ['react', 'react-dom'],
}),
]);
},
},
plugins: [pluginReact()],
});
各配置项的含义与作用如下:
server.port: 3000:Rsbuild 开发服务器端口,即 host 对外地址 http://localhost:3000。tools.rspack回调 +appendPlugins:Rsbuild 推荐通过appendPlugins挂载 Rspack 插件,将ModuleFederationPlugin注入到 Rspack 编译管线。name: 'host':宿主应用在联邦体系中的唯一标识,远程端会通过该标识关联。shareStrategy: 'loaded-first':共享依赖的加载策略——优先使用宿主中已经加载的版本,避免同一依赖被重复加载(配合shared声明生效)。experiments.asyncStartup: true:启用异步启动实验特性,让应用可以异步加载远程模块后再完成启动,对微前端首屏性能更友好。remotes:声明远程应用及其清单地址。与 Module Federation 1.0 直接指向远程入口 JS 不同,2.0 的写法是远程名@http://localhost:300X/mf-manifest.json,通过 manifest 清单文件来描述远程暴露的模块与资源,这是 2.0 的核心变化。shared: ['react', 'react-dom']:将 React 运行时声明为共享依赖,配合loaded-first让 host 与 remote 复用同一份 React,避免多实例导致的 hooks 报错。
远程侧配套配置对比
为了理解 host 的 remotes 是如何被"供应"的,需要对照远程应用的配置:
- remote1(react-manifest-example/remote1/rsbuild.config.ts):
name: 'remote1',通过exposes暴露'./button': './src/button.tsx'与'./app': './src/App.tsx',端口 3001,并配置了dev.assetPrefix: true与dev.client.port: 3001以支持远程模块在开发模式下的资源前缀与 HMR。 - remote2(react-manifest-example/remote2/rsbuild.config.ts):
name: 'remote2',仅暴露'./button': './src/button.tsx',端口 3002,同样启用assetPrefix与client.port。
远程端在开发模式下配置 assetPrefix 是必须的(配置注释中明确说明,生产环境则需配置 output.assetPrefix),否则远程模块的资源 URL 无法正确解析;output.uniqueName 用于保证多个应用在构建产物命名上不冲突。host 的 remotes 中 remote1@http://localhost:3001/mf-manifest.json 即消费这些配置产出的清单。
四、两种消费远程组件的方式
host 的路由页面展示了 Module Federation 2.0 两种典型的远程组件加载方式,路由注册见 react-manifest-example/host/src/App.tsx(/、/remote1、/remote2 三个路由)。
4.1 静态 import(remote1)
react-manifest-example/host/src/pages/remote1.tsx 演示了最直接的方式——在源码中直接导入远程模块:
import Button from 'remote1/button';
function Remote1() {
return (
<div>
<h2>Remote1 Router</h2>
<Button />
</div>
);
}
这里的 remote1/button 命名空间由 host 配置中 remotes.remote1 与 remote1 的 exposes['./button'] 共同决定:remote1 是远程名,button 是暴露的模块名。构建时 @module-federation/enhanced 会解析该导入,并在运行时通过 manifest 获取真实模块。由于 host 启用了 asyncStartup,这类静态导入同样能获得异步加载能力。
4.2 动态 loadRemote(remote2)
react-manifest-example/host/src/pages/remote2.tsx 演示了更具灵活性(可做运行时决策、按需加载)的动态加载方式:
import { loadRemote } from '@module-federation/enhanced/runtime';
import React, { Suspense } from 'react';
const Button = React.lazy(async () => {
const res = await loadRemote('remote2/button');
return res;
});
function Remote2() {
return (
<Suspense fallback={'loading'}>
<h2>Remote2 Router</h2>
<Button />
</Suspense>
);
}
要点拆解:
loadRemote('remote2/button')是运行时 API,返回 Promise,参数同样由"远程名/暴露模块名"组成;- 配合
React.lazy将异步加载结果包装成懒加载组件,再用<Suspense fallback={'loading'}>兜底渲染加载态; - 这种写法可以在不修改构建配置的前提下,将远程模块的加载时机推迟到组件真正渲染时,适合按路由/按权限懒加载的场景。
两种方式可以混合使用,静态导入适合编译期确定、希望打包器静态分析的场景,动态 loadRemote 适合运行时决定加载路径的场景。
五、@mf-types:远程模块的 TypeScript 类型自动生成
host 工程已经预先生成了类型声明目录 react-manifest-example/host/@mf-types,这是 Module Federation 2.0 提供类型安全的关键能力。
5.1 tsconfig 路径映射
react-manifest-example/host/tsconfig.json 通过 paths 把任意模块解析到类型目录:
"paths": {
"*": ["./@mf-types/*"]
}
配合 "include": ["src", "./@mf-types"],编译器在遇到 remote1/button 这类导入时,会先命中 @mf-types/remote1/button.d.ts。
5.2 类型声明的内容
- react-manifest-example/host/@mf-types/index.d.ts:分别对
@module-federation/runtime、@module-federation/enhanced/runtime、@module-federation/runtime-tools三个模块做loadRemote的类型增强,将RemoteKeys收敛为'remote1/button' | 'remote1/app' | 'remote2/button'的联合类型,让loadRemote的参数在编译期即受约束。 - react-manifest-example/host/@mf-types/remote1/apis.d.ts:声明 remote1 的
RemoteKeys,并将PackageType映射到typeof import('remote1/app')、typeof import('remote1/button')。 - react-manifest-example/host/@mf-types/remote1/button.d.ts 与 compiled-types/button.d.ts:给出
Button组件的精确签名export default function Button(): import('react/jsx-runtime').JSX.Element;。
host 的 src/env.d.ts 中还保留了类型增强的注释模板,说明这些声明可由工具自动生成/维护。由此可以看到:@mf-types 让远程模块的 props 类型、导出形状在宿主工程内被完整感知,编译期就能拦截"导入不存在的远程模块"或"组件 props 传错"这类错误,这正是 Module Federation 2.0 相比 1.0 在工程化体验上的重要提升。
六、运行效果与验证路径
启动后,在 host(http://localhost:3000)中通过顶部导航(react-manifest-example/host/src/navigation.tsx 基于 antd Menu 实现)可切换三个页面:
- Home(pages/Home.tsx):antd Table 演示页,纯宿主侧内容,不依赖远程;
- Remote1:渲染来自 remote1 的按钮组件(内容为 "remote1");
- Remote2:通过
loadRemote懒加载 remote2 的按钮组件(内容为 "Remote2 button")。
remote1 与 remote2 的应用本体(remote1/src/App.tsx、remote2/src/App.tsx)自带 react-router-dom 子路由与 antd 图片示例,可独立访问其自身端口验证 HMR 生效;host 通过 manifest 引用它们暴露的 ./button、./app 模块,实现"宿主统一编排、远程独立部署与热更新"的微前端效果。
七、小结
结合 react-manifest-example/host/README.md 的标准 Rsbuild 流程与仓库源码,可以得到 host 应用落地 Module Federation 2.0 的完整范式:
- 配置:在
rsbuild.config.ts中用ModuleFederationPlugin(来自@module-federation/enhanced/rspack)声明remotes指向mf-manifest.json,并开启asyncStartup、loaded-first与shared依赖共享; - 接入:静态
import 'remote1/button'与动态loadRemote('remote2/button') + React.lazy + Suspense两种方式按需选用; - 类型安全:通过 tsconfig 的
paths映射到@mf-types,让远程模块获得完整类型约束; - 运行:
pnpm install/pnpm dev/pnpm build/pnpm preview覆盖开发、构建、预览全流程,host 与 remote 分别监听 3000/3001/3002 端口。
在此基础上,可以进一步在 react-manifest-example 仓库内对比其他示例(如 dynamic-remotes)了解动态远程加载的更多形态,为生产级微前端架构提供参考。