如何配置 graphql-codegen 在 Vite 项目中自动生成类型和 Hook?
解读
国内一线团队普遍把 GraphQL 作为 BFF 层的主力协议,而 Vite 又是工程化首选。面试官问“怎么在 Vite 里跑 graphql-codegen”,表面看是工具链集成,实则考察三点:
- 是否理解 Vite 的“按需编译”与 codegen 的“预生成”之间的节奏差异;
- 能否把 codegen 的产物无缝接入 TypeScript 与 ESLint 体系,避免 CI 失败;
- 是否具备插件化思维——用最小侵入方式让生成逻辑成为“开发服务器”的一部分,而不是额外脚本。
答不到“热更新触发重新生成”和“产物路径别名”这两个细节,基本会被判定为“只跑通过 demo”。
知识点
- Vite 插件生命周期:configResolved、configureServer、handleHotUpdate
- graphql-codegen 核心配置:schema、documents、generates、plugins 四元组
- TypeScript 路径别名与 Vite resolve.alias 同步
- 热更新粒度:gql 文件变动 → codegen → 触发 TS 重新检查 → 浏览器 HMR
- 国内网络:pnpm + 淘宝镜像源,锁定 codegen 版本避免 day-one 失败
- CI 场景:husky + lint-staged 保证“无生成不提交”,防止产物漂移
答案
- 安装依赖(pnpm 为例,国内镜像)
pnpm add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-query
- 在项目根新建 codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql', // 国内 BFF 地址
documents: ['src/**/*.{ts,tsx}', '!src/gql/**/*'], // 排除产物目录
ignoreNoDocuments: true,
generates: {
'src/gql/': {
preset: 'client',
plugins: [],
config: {
useTypeImports: true,
skipTypename: false,
enumsAsTypes: true,
reactQueryVersion: 5,
},
},
},
hooks: { afterOneFileWrite: ['prettier --write'] },
}
export default config
- 封装 Vite 插件 vite-plugin-graphql-codegen.ts
import { exec } from 'child_process'
import { promisify } from 'util'
import type { Plugin } from 'vite'
const runGenerate = promisify(exec)
export default function gqlCodegen(): Plugin {
let serverRestarting = false
return {
name: 'vite:gql-codegen',
apply: 'serve',
async configureServer(server) {
// 首次启动生成一次
await runGenerate('pnpm codegen')
server.ws.send('full-reload')
},
async handleHotUpdate({ file, server }) {
if (file.endsWith('.gql') || file.endsWith('.graphql')) {
if (serverRestarting) return
serverRestarting = true
await runGenerate('pnpm codegen')
server.ws.send('full-reload')
serverRestarting = false
}
},
}
}
- 在 vite.config.ts 引入
import gqlCodegen from './vite-plugin-graphql-codegen'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [gqlCodegen(), react()],
resolve: {
alias: {
'@gql': '/src/gql', // 与 tsconfig 同步
},
},
})
- tsconfig.json 补全
{
"compilerOptions": {
"paths": {
"@gql/*": ["src/gql/*"]
}
}
}
- package.json 脚本
{
"scripts": {
"codegen": "graphql-codegen --config codegen.ts",
"dev": "vite",
"build": "pnpm codegen && tsc && vite build"
}
}
- 使用示例
import { graphql } from '@gql/gql'
import { useQuery } from '@tanstack/react-query'
const UserList = graphql(`
query UserList($first: Int!) {
users(first: $first) {
id
name
}
}
`)
export default function Users() {
const { data } = useQuery({
queryKey: ['users', 10],
queryFn: ({ queryKey }) => request('/graphql', UserList, { first: queryKey[1] }),
})
return <div>{data?.users.map(u => u.name)}</div>
}
至此,保存任意 .gql 文件,Vite 开发服务器会秒级重新生成类型与 React-Query Hook,浏览器无刷新拿到最新接口类型。
拓展思考
- Monorepo 场景:把 codegen 抽成独立 package,通过 pnpm workspace 协议共享 schema,避免每个子应用重复生成。
- 服务端渲染:在 SSR 模式下,codegen 产物需同时被 Node 端与浏览器端引用,需把
src/gql加入optimizeDeps.include,防止预构建重复加载。 - 灰度发布:利用 graphql-codegen 的
schema: [{ http://gray-api.internal:4000/graphql }, { http://stable-api.internal:4000/graphql }]数组写法,一次生成两套类型,配合运行时开关做灰度。 - 性能上限:当 schema 超过 10 MB(国内某电商商品中心真实案例),可把
documents拆成多进程扫描,或改用@graphql-codegen/cli的watch模式,避免 Vite 插件阻塞主线程。 - 合规要求:金融、医疗项目需把生成目录设为
gitignore,CI 强制重新生成,确保审计可追溯;同时把 codegen 产物加入 SonarQube 排除规则,防止误报重复代码。