module-federation-examples 实战:Apollo Client 与 Module Federation 的跨应用数据共享(含 SSR)
module-federation-examples 实战:Apollo Client 与 Module Federation 的跨应用数据共享(含 SSR)
本文基于 apollo-client 示例,讲解如何在 Module Federation(模块联邦)环境中使用 Apollo Client:app1 作为宿主应用通过 React.lazy 加载 app2 暴露的 PokemonList 组件,两个应用各自持有带 GraphQL 查询的组件,通过联邦共享依赖保证 @apollo/client 单例,并完整演示了服务端渲染(SSR)下 Apollo 数据缓存的序列化与恢复流程。读完后你将掌握:联邦插件的 client/server 双端配置、共享依赖的 singleton/eager 参数用法、remoteEntry.js 在 Node 端联邦的加载方式,以及 renderToStringWithData 配合 __CLIENT_CONFIG__ 实现 SSR 数据注水的方法。
示例应用架构:两个独立部署的联邦应用
该示例包含两个完全独立构建、独立部署的 Express 应用:
app1(消费方):消费app2暴露的PokemonList组件,并通过React.lazy将其拆分为独立 chunk 异步加载;app2(提供方):暴露PokemonList组件,该组件内部携带自己的 GraphQL 查询(查询 PokéAPI 的pokemons接口)。
原文档提到的 Content 组件与 userRoute 路由在源码中已被替换为 PokemonList 组件,实际代码中以 app2 的 module-federation.js 中 exposes 配置为准:
exposes: {
'./PokemonList': './src/client/components/PokemonList',
},
两个应用均基于 React 18.3.1 + @apollo/client 3.14.0 + graphql 16.x 构建,服务端使用 Express,并可通过 Rspack(默认)或 Webpack(legacy:* 脚本)两种打包器构建,构建与联邦插件配置详见 app1/package.json。
端口映射(对应 apollo-client/README.md 的 Running Demo 一节):
- http://localhost:3000/(app1,消费
app2/PokemonList) - http://localhost:3001/(app2,独立渲染同一组件)
运行示例
在仓库中进入 apollo-client 目录执行:
yarn # 或 pnpm install,安装依赖
pnpm run start # 构建并启动所有应用
各脚本的实际行为可以从 apollo-client/package.json 与各应用的 package.json 中确认:
| 脚本 | 行为 |
|---|---|
pnpm start |
通过 pnpm --filter apollo-client_* --parallel start 并行启动 app1/app2 |
pnpm build |
并行执行两个应用的 pnpm build(先 build:server 再 build:client,默认使用 Rspack) |
pnpm serve |
并行执行 node dist/server/main.js 启动 Express 服务 |
pnpm legacy:start / legacy:build |
使用 Webpack 配置的等价流程(config/webpack.client.js、config/webpack.server.js) |
两个应用的 serve 之间存在启动顺序依赖:app1 的脚本为 wait-on tcp:3002 && node dist/server/main.js,app2 为 sleep 3 && node dist/server/main.js,保证宿主应用在提供方构建完成后启动,避免联邦 remoteEntry.js 拉取失败。
E2E 验证通过 Playwright 完成,apollo-client/e2e/checkCraApps.spec.ts 访问 http://localhost:3001 并断言标题 Module Federation Example: React 18 + Apollo Client 与 This is the App 2 application. 标题可见;apollo-client/playwright.config.ts 通过 webServer 配置(pnpm build && pnpm serve,端口 3001)自动拉起服务。执行 pnpm run e2e:ci(即 npx playwright test)即可完成端到端验证。
联邦插件配置:client 与 server 双端实例
两个应用共用的联邦配置都收敛在一个工厂函数里,以 app1/config/module-federation.js 为例:
module.exports = FederationPlugin => ({
client: new FederationPlugin({
remoteType: 'script',
name: 'app1',
filename: 'remoteEntry.js',
remotes: {
app2: 'app2@http://localhost:3001/static/remoteEntry.js',
},
shared: sharedDependencies,
}),
server: [
new FederationPlugin({
remoteType: 'script',
name: 'app1',
library: { type: 'commonjs-module', name: 'app1' },
filename: 'remoteEntry.js',
remotes: {
app2: 'app2@http://localhost:3001/server/remoteEntry.js',
},
runtimePlugins: [require.resolve('@module-federation/node/runtimePlugin')],
shared: sharedDependencies,
}),
],
});
工厂参数 FederationPlugin 由构建工具注入,同一份配置同时服务于两种构建器:app1/config/webpack.client.js 注入 @module-federation/enhanced/webpack 导出的 ModuleFederationPlugin,app1/config/rspack.client.js 注入 @module-federation/enhanced/rspack 的实现,webpack.client.js、webpack.server.js、rspack.client.js、rspack.server.js 分别通过 plugins: [getModuleFederationPlugin(...).client] 或 plugins: [...getModuleFederationPlugin(...).server] 挂载对应端插件。
关键参数说明(client 端):
name: 'app1':当前应用在共享作用域中的联邦名称;filename: 'remoteEntry.js':联邦入口产物名,即其他应用加载本应用的地址;remotes:声明依赖的远端应用,app2@http://localhost:3001/static/remoteEntry.js中app2是本地别名,浏览器端通过script标签(remoteType: 'script')加载该 URL;shared:共享依赖声明,见下一节。
server 端与 client 端的差异要点:
library: { type: 'commonjs-module', name: 'app1' }:Node 端以 CommonJS 模块形式暴露,配合打包配置中的output.libraryTarget: 'commonjs-module'(见 app1/config/webpack.server.js);remotes指向http://localhost:3001/server/remoteEntry.js:注意 server 端 remote 地址与 client 端不同(/server/前缀)。这一路径在 app1/src/server/middleware.ts 中通过app.use('/server', express.static(path.join(process.cwd(), 'dist/server')))暴露,即把dist/server目录整体作为静态资源提供(源码中附有 WARNING 注释,提示这会暴露所有服务端文件,生产环境应自行收敛);runtimePlugins: [require.resolve('@module-federation/node/runtimePlugin')]:引入@module-federation/node(版本 2.7.32)的运行时插件,负责在 Node 环境中完成远端入口的下载、编译与加载,这是 Node 端联邦能跨进程加载app2编译产物的核心。
共享依赖:@apollo/client 的 singleton 与 eager
示例的共享依赖清单(app1 使用对象形式声明,见 app1/config/module-federation.js):
const sharedDependencies = {
react: { requiredVersion: deps.react, eager: true },
'react-dom': deps['react-dom'],
graphql: { requiredVersion: deps.graphql, eager: true },
'@apollo/client': {
eager: true,
singleton: true,
requiredVersion: deps['@apollo/client'],
},
'node-fetch': deps['node-fetch'],
'serialize-javascript': deps['serialize-javascript'],
};
版本均从 package.json 的 dependencies 动态读取(deps.react 为 18.3.1,deps<a href="https://link.gitcode.com/i/77e41f4945c1e2ed05bc38241b1b378d" target="_blank">'@apollo/client'] 为 ^3.14.0 等),避免版本号在依赖升级后漂移。app2 侧([app2/config/module-federation.js)则以数组形式 shared: [{ react, 'react-dom', graphql, '@apollo/client': {...}, 'node-fetch', 'serialize-javascript' }] 声明完全一致的依赖集。
针对 Apollo Client 场景,两个参数尤其关键:
singleton: true:强制宿主与远端复用同一个@apollo/client模块实例。若未设单例,app2的PokemonList内部通过useQuery使用的 Apollo 上下文与app1的ApolloProvider将来自两份不同的库副本,导致 Provider 数据无法被远端组件消费;eager: true(react、graphql、@apollo/client):让共享依赖以同步方式打入入口,而非按promise方式异步协商加载,保证首屏渲染与 SSR 场景下依赖已就绪;node-fetch与serialize-javascript列入 shared:前者是 SSR 端为createHttpLink提供 fetch 实现的依赖,后者用于把服务端 Apollo 缓存序列化进 HTML,两端需要同一版本以避免行为差异。
消费端代码:React.lazy 加载远端组件
app1 的 src/client/components/App.tsx 是消费 app2 组件的核心:
import type { PokemonListProps } from 'app2/PokemonList';
const PokemonList = React.lazy(
() => import('app2/PokemonList') as Promise<{ default: React.FC<PokemonListProps> }>,
);
import('app2/PokemonList')由联邦运行时解析为对http://localhost:3001/static/remoteEntry.js的加载与远端模块请求,React.lazy将其包裹成代码分割 chunk,加载期间由<React.Suspense fallback={<span>Suspense Loading....</span>}>提供降级 UI;app1内还有limit/offset两个 range 滑块(取值 1~100),作为 props 传给远端组件,驱动 GraphQL 查询变量变化。
组件本体在 app2/src/client/components/PokemonList.tsx:
export const GET_POKEMONS = gql`
query pokemons($limit: Int, $offset: Int) {
pokemons(limit: $limit, offset: $offset) {
count next previous status message
results { url name image }
}
}
`;
const PokemonList: React.FC<PokemonListProps> = ({ limit, offset }) => {
const { loading, error, data } = useQuery(GET_POKEMONS, {
variables: { limit, offset },
fetchPolicy: 'cache-first',
});
// ...
};
该组件即“带着自己的 GraphQL 查询一起被联邦出去”的典型形态:查询文档 gql 常量、useQuery 调用、fetchPolicy: 'cache-first' 缓存策略都定义在提供方一侧,消费方只负责传参。cache-first 策略与下面的 SSR 注水直接相关——客户端恢复缓存后,命中缓存的查询将直接读缓存而非重新发起网络请求。
TypeScript 跨应用类型提示
app1 通过 apollo-client/app1/index.d.ts 声明远端模块类型:
declare module 'app2/PokemonList' {
export { GET_POKEMONS, PokemonListProps, default } from '@app2/client/components/PokemonList';
}
其中 @app2/* 由 apollo-client/tsconfig.base.json 的 paths 映射到 ./app2/src/*,从而让 IDE 直接引用提供方源码推导类型,避免为远端组件手工编写重复的类型声明。
SSR 数据流:renderToStringWithData 与缓存注水
两个应用的服务器渲染逻辑一致,以 app1/src/server/render.tsx 为例:
export default async (req, res, next) => {
const fetch = (await import('node-fetch')).default;
const helmet = Helmet.renderStatic();
const { apolloClient } = createApolloClient({ ssrMode: true, fetch });
const markup = await renderToStringWithData(
<ApolloProvider client={apolloClient}>
<App />,
</ApolloProvider>,
);
const apolloData = apolloClient.extract();
const serverRenderedApplicationState = { apolloData };
res.write(`<div id="root">${markup}</div>`);
res.write(
`<script>window.__CLIENT_CONFIG__ = ${serialize(serverRenderedApplicationState)}</script>`,
);
res.write(`<script async data-chunk="main" src="http://localhost:3000/static/main.js"></script>`);
res.send();
};
整个 SSR 数据流分为四步:
- 服务端创建独立 Apollo 实例:src/client/apolloClient.ts 中的
createApolloClient({ ssrMode, fetch })每次返回新的InMemoryCache+ApolloClient,ssrMode: true使 Apollo 在 SSR 期间按官方要求不向缓存写入重复数据;link使用createHttpLink({ uri: 'https://graphql-pokeapi.graphcdn.app', fetch })指向公开 GraphQL 端点——源码注释明确说明必须显式传入 fetch polyfill(Node 环境下为node-fetch2.7.0); - 等待数据就绪后渲染:
renderToStringWithData(来自@apollo/client/react/ssr)会等待useQuery的初始数据加载完成再执行renderToString,保证首屏 HTML 已包含查询结果; - 缓存序列化注水:
apolloClient.extract()提取当前 InMemoryCache 内容,经serialize-javascript安全序列化后写入window.__CLIENT_CONFIG__; - 客户端恢复缓存并 hydrate:src/client/index.tsx 在浏览器中执行
apolloCache.restore(window['__CLIENT_CONFIG__'].apolloData)后再ReactDOMClient.hydrateRoot(<ApolloProvider client={apolloClient}>...),使首屏 React 水合与远端组件的cache-first查询都能直接命中服务端拉取的数据。
请求入口由 app1/src/server/middleware.ts 装配:/static 提供 dist/client 静态资源,app.get('/*', serverRender) 将全部路由交给 server-entry.ts(其内部 await import('./render') 后调用渲染中间件),最终由 app1/src/server/index.ts 的 Express 实例监听 3000 端口(app2 对应监听 3001)。
小结:本示例覆盖的工程要点
| 技术点 | 对应实现 |
|---|---|
| 远端组件代码分割 | React.lazy(() => import('app2/PokemonList')) + React.Suspense |
| 共享依赖单例 | @apollo/client 声明 singleton: true、核心依赖 eager: true |
| Node 端跨进程联邦 | @module-federation/node runtimePlugin + /server/remoteEntry.js 静态暴露 |
| SSR 数据注水 | renderToStringWithData + apolloClient.extract() + window.__CLIENT_CONFIG__ + apolloCache.restore() |
| 双构建器支持 | 同一份 module-federation.js 工厂注入 webpack / rspack 的 ModuleFederationPlugin |
| 端到端验证 | Playwright 测试 + webServer 自动拉起服务 |
需要说明的适用前提:GraphQL 请求指向公开端点 https://graphql-pokeapi.graphcdn.app,运行演示与 E2E 测试需要网络可达;/server 静态目录直接暴露 dist/server(源码已附 WARNING 注释),该配置仅适合演示环境,生产部署应调整静态资源暴露范围。