Module Federation 实战:在 react-host-nextjs-remote 示例中运行与配置 Next.js Remote 应用

原创2026-10-14 18:50:261,994 阅读
文章标签:示例工程微前端前端

Module Federation 实战:在 react-host-nextjs-remote 示例中运行与配置 Next.js Remote 应用

本指南以 react-nextjs/react-host-nextjs-remote/remote/ 目录下的 Next.js Remote 应用为研究对象,系统讲解如何在 module-federation-examples 仓库中启动、开发、配置并验证这个作为模块联邦远端(Remote)的 Next.js 应用。阅读完本文,你将掌握 Remote 侧的启动命令、开发热更新机制、API 路由组织方式,以及基于 @module-federation/nextjs-mf 的 NextFederationPlugin 完整配置方法,并了解它与 React Host(8080 端口)之间的消费关系。

一、示例整体定位:React Host 与 Next.js Remote

该示例位于仓库的 react-nextjs/react-host-nextjs-remote 目录,属于 react-nextjs 工作区下的四种模块联邦组合之一(React Host + NextJS Remote)。依据 react-nextjs/README.md 的说明,示例包含两种角色:

  • Host(React 应用):运行在 8080 端口,是依赖 Remote 暴露模块的顶层应用;
  • Remote(Next.js 应用):运行在 8081 端口,向 Host 暴露组件。

示例根目录的 package.json 通过 concurrently 同时启动两个应用:

"start": "concurrently \"cd host; npm run dev\" \"cd remote; npm run dev\""

因此从示例根目录执行 npm run start,即可让 Host 与 Remote 同时就绪,随后在浏览器访问 http://localhost:8080/ 查看整体效果。

二、启动 Remote 开发服务器:从 README 到仓库真实端口

remote/README.md 首先说明这是一个通过 create-next-app 初始化的 Next.js 项目,并给出标准的开发服务器启动方式:

npm run dev
# 或
yarn dev

README 中提示打开 http://localhost:3000 查看效果。不过在当前仓库的上下文里,Remote 应用实际运行在 8081 端口,这是由其自身的 remote/package.json 决定的:

"scripts": {
  "dev": "NEXT_PRIVATE_LOCAL_WEBPACK=true next dev -p 8081",
  "build": "NEXT_PRIVATE_LOCAL_WEBPACK=true next build",
  "start": "next start"
}

需要注意两个关键点:

  1. 端口由 -p 8081 显式指定,与 Host 的 8080 端口错开,避免两个本地服务冲突,也与模块联邦的 remoteEntry 加载地址保持一致;
  2. NEXT_PRIVATE_LOCAL_WEBPACK=true 环境变量:该变量使 Next.js 使用本地 webpack 实例,这是 @module-federation/nextjs-mf 插件能够注入 NextFederationPlugin 的必要前提。

另外,remote/package.json 中的 predev、prestart 钩子都会执行仓库根目录的 scripts/track-demo-run.js,用于记录示例的运行情况,属于仓库统一的分析埋点,不影响开发流程本身。

三、开发体验:修改页面自动更新与 API 路由

README 明确指出,可以通过修改 pages/index.js 来编辑页面内容,保存后页面会自动更新(热更新)。在 Remote 应用中,入口页面位于 remote/pages/index.js,它是一个标准的 Next.js 页面组件,使用了 next/head、next/image 以及 Home.module.css 样式。

同时,README 介绍了 Next.js 的 API 路由(API Routes) 机制:

  • pages/api 目录会被映射为 /api/*;
  • 该目录下的文件被视为 API 路由而非 React 页面;
  • 示例端点可通过 http://localhost:3000/api/hello 访问,对应文件为 pages/api/hello.js。

在仓库中,这个端点实现位于 remote/pages/api/hello.js。由于 Remote 实际运行在 8081 端口,本地访问时应使用 http://localhost:8081/api/hello。这正好体现了 Next.js "同目录同时承载页面与接口" 的特性:页面路由与 API 路由在模块联邦场景下可以同时暴露给 Host 使用。

四、模块联邦核心配置:next.config.js 深度解析

Remote 的模块联邦能力集中在 remote/next.config.js,这是理解整个示例"如何把 Next.js 应用变成模块联邦 Remote"的关键文件:

const NextFederationPlugin = require('@module-federation/nextjs-mf');

module.exports = {
  webpack(config, options) {
    if (!options.isServer) {
      config.plugins.push(
        new NextFederationPlugin({
          name: 'remote',
          remotes: {},
          filename: 'static/chunks/remoteEntry.js',
          exposes: {
            './nextjs-remote-component': './components/nextjs-remote-component.js',
            './nextjs-remote-page': './pages/index.js',
          },
          shared: {
            react: {
              requiredVersion: false,
              singleton: true,
            },
          },
        }),
      );
    }
    return config;
  },
  reactStrictMode: true,
};

各配置项的含义与作用如下:

配置项 当前取值 作用说明
name 'remote' 定义 Remote 的唯一名称,Host 通过该名称在 remotes 中引用它
remotes {} 本应用作为纯 Remote 不消费其他远端,因此为空
filename 'static/chunks/remoteEntry.js' 生成 remoteEntry 清单文件的路径。Next.js 的产物会落在 /_next/ 下,因此 Host 侧实际引用的完整地址为 http://localhost:8081/_next/static/chunks/remoteEntry.js
exposes 两个组件入口 对外暴露的模块映射,Host 通过 remote/xxx 的形式导入
shared react 单例共享 声明 react 为单例(singleton: true),并关闭版本强校验(requiredVersion: false),避免 Host 与 Remote 出现双 React 实例

值得注意的细节:

  1. 只在客户端注入插件:if (!options.isServer) 判断确保插件只在浏览器端构建时生效,这是 Next.js 模块联邦的常见做法,因为 remoteEntry 面向浏览器加载;
  2. reactStrictMode: true:这是 next.config.js 中原有的 Next.js 配置项,与模块联邦配置共存于同一配置文件中;
  3. 依赖版本:根据 remote/package.json,插件版本为 @module-federation/nextjs-mf@8.8.56,配套 Next.js 12.3.4、React 18.3.1。同时 react-nextjs/README.md 提示,对于 Next.js 应用需要使用较新版本的 @module-federation/nextjs-mf(该仓库注明其为付费模块),这是选择此方案前需要了解的版本与授权前提。

五、exposes 的源码实现:被暴露的两个组件

exposes 暴露了两个模块,均可在 Host 中以 remote/xxx 导入:

1. ./nextjs-remote-component

对应 remote/components/nextjs-remote-component.js。这是一个纯展示型 React 组件,渲染一个 cadetblue 背景的全宽导航条,居中展示文案:

Hello from Remote Nextjs component hosted on localhost:8081

该组件不依赖任何外部样式文件(Home.module.css 的导入在源码中被注释掉),因此作为联邦模块加载时样式隔离风险极低。

2. ./nextjs-remote-page

对应 remote/pages/index.js(即第二节中提到的入口页面)。注意 exposes 直接将整个 Next.js 页面作为模块暴露,这意味着 Host 可以把 Remote 的完整页面当作一个组件来挂载。

此外,目录下还存在 remote/components/nextjs-remote-page.js,它渲染的是与组件几乎一致的导航条文案。从源码结构可以推断,该文件与 pages/index.js 形成"页面 + 组件"的双入口设计,便于 Host 分别以页面级或组件级粒度消费 Remote 能力。

六、Host 侧如何消费 Remote 暴露的模块

要完整理解 Remote 的配置价值,需要看 Host 的对应消费配置,位于 host/webpack.config.js:

new ModuleFederationPlugin({
  experiments: { asyncStartup: true },
  name: 'host',
  shareStrategy: 'loaded-first',
  filename: 'remoteEntry.js',
  remotes: {
    remote: 'remote@http://localhost:8081/_next/static/chunks/remoteEntry.js',
  },
  exposes: {},
  shared: {
    react: {
      requiredVersion: false,
      singleton: true,
    },
  },
}),

与 Remote 侧配置对照,可以看到完整的调用链:

  • Host 的 remotes.remote 指向 http://localhost:8081/_next/static/chunks/remoteEntry.js,正好对应 Remote 侧 filename: 'static/chunks/remoteEntry.js' 在 /_next/ 下的产物地址;
  • 两端的 shared.react 配置保持一致(singleton: true、requiredVersion: false),保证 React 实例在两端共享;
  • Host 使用 @module-federation/enhanced 的 ModuleFederationPlugin,并开启 asyncStartup 实验特性。

实际消费发生在 host/src/App.jsx:

import NextjsRemoteComponent from 'remote/nextjs-remote-component';
import NextjsRemotePage from 'remote/nextjs-remote-page';

function App() {
  return (
    <>
      <div>This is the React container App hosted at localhost:8080</div>
      <NextjsRemoteComponent />
      <NextjsRemotePage />
    </>
  );
}

可以看到,remote/nextjs-remote-component 与 remote/nextjs-remote-page 的导入路径,正是 Remote 侧 exposes 中定义的模块名。Host 渲染时,NextjsRemoteComponent 与 NextjsRemotePage 都会显示来自 8081 端口的远端内容。

七、端到端验证:Playwright 测试如何确认联邦生效

仓库为该示例提供了自动化验证,位于 e2e/CommonCheck.spec.ts。测试逻辑如下:

  1. 分别访问 http://localhost:8080/ 与 http://localhost:8081/,断言两个应用都能正常打开;
  2. 在 8080(Host)页面中,断言"容器应用"文案可见;
  3. 在 8080 页面中,断言来自 Remote 的导航条文案可见。

测试断言的文案定义在 playwright-e2e/fixtures/constants.ts:

  • header:This is the React container App hosted at localhost:8080(Host 自身内容);
  • nav:Hello from Remote Nextjs component hosted on localhost:8081(Remote 暴露的内容)。

这条测试链非常有价值:如果 Host 页面中出现了 8081 端口的文案,就证明模块联邦的 remoteEntry 加载、模块解析与渲染全链路是通的。从源码结构看,CommonCheck.spec.ts 复用了仓库根目录 playwright-e2e 下的公共选择器与常量夹具,这为在 CI 中批量验证各示例提供了统一基础。

八、构建与部署

除开发模式外,Remote 同样支持生产构建。依据 remote/package.json:

  • npm run build:执行 NEXT_PRIVATE_LOCAL_WEBPACK=true next build 生成生产构建产物;
  • npm run start:执行 next start 启动生产服务器。

remote/README.md 提到可将应用部署到 Vercel 平台,并建议查阅 Next.js 的部署文档。需要说明的是,这部分内容来自 create-next-app 的通用模板说明;对于本示例,实际部署时仍需保证 Host 能够通过网络访问 Remote 的 remoteEntry.js 地址(即 /_next/static/chunks/remoteEntry.js),因此两个应用需要部署在可互相访问的位置,并相应调整 Host 侧 remotes 中的 URL。

结语与关键文件索引

本文完整覆盖了 remote/README.md 中关于启动、开发与部署的全部要点,并结合仓库源码补充了端口差异、模块联邦配置与端到端验证细节。核心文件汇总如下,便于继续深入阅读:

文件 作用
remote/next.config.js Remote 的模块联邦核心配置(NextFederationPlugin、exposes、shared)
remote/package.json 端口 8081、构建命令与依赖版本
remote/pages/index.js 被 exposes 暴露的页面模块
remote/components/nextjs-remote-component.js 被 exposes 暴露的组件模块
host/webpack.config.js Host 消费 Remote 的 remotes 配置
host/src/App.jsx Host 实际导入并渲染远端模块的代码
e2e/CommonCheck.spec.ts 验证联邦链路是否正常的 Playwright 测试

按仓库根目录 package.json 的约定安装依赖后,从 react-nextjs/react-host-nextjs-remote 目录执行 npm run start,即可在 http://localhost:8080/ 看到 React Host 与 Next.js Remote 协同工作的完整效果。

登录后查看全文
module-federation-examples