如何在 Webpack 中为 SSR 与 CSR 分别配置不同的 Apollo 客户端?
解读
国内主流招聘场景下,面试官抛出此题并非单纯考察“写配置”,而是验证候选人是否真正落地过“同构渲染 + GraphQL”项目。核心痛点有三:
- 服务端需要“无 DOM、无 window、无 cookie”的纯净客户端,且必须支持缓存、数据脱水;
- 浏览器端需要“带认证、带缓存恢复、带 WebSocket 订阅”的富客户端;
- 同一份业务代码在两端都被引用,Webpack 打包时不能出现“服务端代码被打进浏览器包”或“浏览器依赖在 Node 环境报错”的泄露。
因此,答案必须体现“构建层隔离 + 运行时注入 + 代码分割”三位一体思路,并给出可落地的配置片段与目录规范。
知识点
- Webpack 多配置(multi-compiler)与 target 区别:target: 'node' 会关闭打包内置模块、关闭 HMR、关闭代码分割;target: 'web' 则相反。
- webpack.DefinePlugin 注入 BUILD_TARGET 常量,实现“同文件不同分支”编译时 Tree-Shaking。
- externals 白名单:服务端 bundle 需把 node_modules 全部外置,但 apollo-client 自身若用 ESM 需保留,否则出现“双实例”问题。
- resolve.alias 映射:把
apollo-client指向两份不同工厂文件,例如@/apollo/ssr.js与@/apollo/csr.js,实现“同 import 不同实现”。 - 代码分割与运行时替换:浏览器端利用 APOLLO_STATE 脱水,服务端利用 cache.extract() 注水;Webpack 只需保证 json 文件不被当作 asset 重复打包。
- 国内部署常遇“阿里容器只支持 Node 14”场景,需关闭 apollo 3.x 的 React 18 依赖警告,可在 alias 中把
@apollo/client/react指向空模块,避免把 React 打进去。
答案
(1)目录规范
src/
├─ apollo/
│ ├─ index.js // 统一导出:export { getClient } from './' + BUILD_TARGET
│ ├─ ssr.js // 创建 ApolloClient,cache: new InMemoryCache(), ssrMode: true
│ └─ csr.js // 创建 ApolloClient,cache: new InMemoryCache().restore(window.__APOLLO_STATE__),link 带 auth + ws
├─ pages/
└─ server/
└─ render.js // 调用 getClient() 拉数据,把 cache.extract() 注入 HTML
(2)webpack.server.js(Node 端)
const path = require('path');
module.exports = {
target: 'node',
entry: './src/server/index.js',
output: {
path: path.resolve('dist/server'),
filename: 'server.js',
libraryTarget: 'commonjs2'
},
externals: [
// 保留 apollo 自身,其余全部外置
({ request }, cb) => {
if (/^@apollo\/client/.test(request)) return cb();
cb(null, 'commonjs ' + request);
}
],
plugins: [
new webpack.DefinePlugin({
BUILD_TARGET: JSON.stringify('ssr')
})
],
resolve: {
alias: {
'@': path.resolve('src')
}
},
module: { rules: [{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }] }
};
(3)webpack.client.js(浏览器端)
module.exports = {
target: 'web',
entry: './src/client/index.js',
output: {
path: path.resolve('dist/client'),
filename: '[name].[contenthash].js'
},
plugins: [
new webpack.DefinePlugin({
BUILD_TARGET: JSON.stringify('csr')
})
],
optimization: {
splitChunks: { chunks: 'all' }
},
resolve: { alias: { '@': path.resolve('src') } },
module: { rules: [{ test: /\.js$/, use: 'babel-loader', exclude: /node_modules/ }] }
};
(4)apollo/index.js(编译时分支)
// 利用 DefinePlugin 在编译阶段把未使用分支 Tree-Shaking 掉
if (BUILD_TARGET === 'ssr') {
module.exports = require('./ssr');
} else {
module.exports = require('./csr');
}
(5)服务端渲染入口
import { getClient } from '@/apollo';
const client = getClient(); // 拿到 ssr 实例
const App = (
<ApolloProvider client={client}>
<StaticRouter location={req.url}>
<MyApp />
</StaticRouter>
</ApolloProvider>
);
await getDataFromTree(App);
const html = ReactDOMServer.renderToString(App);
res.send(`
<!doctype html>
<html>
<body>
<div id="root">${html}</div>
<script>
window.__APOLLO_STATE__ = ${JSON.stringify(client.cache.extract()).replace(/</g, '\\u003c')}
</script>
<script src="/client/main.${hash}.js"></script>
</body>
</html>
`);
至此,SSR 与 CSR 各自拥有独立的 Apollo 客户端,构建层零运行时开销,业务代码零分支判断,完全符合国内大厂“同构直出 + 首屏性能”考核标准。
拓展思考
- 微前端场景:子应用也采用同构,如何在主应用 Shell 里共享一份 Apollo cache?
思路:把 cache 序列化到主应用的 globalThis.SHARED_APOLLO,子应用通过 webpack.ModuleFederationPlugin 的 shared 配置把 @apollo/client 提升为 singleton,并在 getClient() 中优先恢复全局缓存。 - 边缘渲染(Edge SSR)如 Vercel、阿里云 ESR:Node 环境无文件系统,InMemoryCache 过大可能导致内存溢出,可改用 apollo-cache-redis 并借助 webpack 的 externals 把 ioredis 外置,利用边缘函数提供的 Redis 绑定。
- 国内低网速场景:可把 apollo 的查询哈希与变量做组合,生成稳定文件名,通过 webpack 的 assetModule 把查询结果预打包成静态 json,实现“离线优先”的 PWA 体验,同时减少 SSR 实时请求压力。