用途:GraphQL Code Generator 用于从 GraphQL schema 和查询/变更操作自动生成 TypeScript 类型、React hooks 等代码,让 GraphQL 调用获得类型检查。
主要能力:通过插件生成不同产物,typescript 生成基础类型,typescript-operations 生成查询/变更类型,typescript-react-apollo 生成 React hooks,typescript-urql 生成 URQL hooks,introspection 输出 schema JSON。支持自定义标量映射、枚举作为类型、生成 hooks 等配置。
使用方式:先安装依赖,命令为 npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo @parcel/watcher。再创建 codegen.ts 配置,指定 schema、documents 与 generates 输出及插件。可在 package.json 添加脚本:graphql-codegen --config codegen.ts 与 graphql-codegen --config codegen.ts --watch。之后在 .graphql 或 .tsx 中定义操作,运行生成后导入生成的类型与 hooks 使用。
适用场景:React + Apollo 或 URQL 项目、需要类型安全 GraphQL 调用的前端工程。支持多输出、import-types 预设、near-operation-file 预设与 client 预设(含 fragmentMasking)。
限制与排错:类型不更新可删除生成目录;schema 获取失败需在配置中添加请求头;重复类型可用 import-types 预设;watch 不工作需安装 @parcel/watcher。可用 npx graphql-codegen --verbose 与 --check 调试。资料未提供收费、价格与平台信息。