GraphQL Codegen CLI处理Fragment文件失败的求助
GitHub GraphQL Fragment 提取与 Codegen 配置示例
单文件 Fragment + 查询 写法
把Fragment和查询放在同一个.graphql文件里,Fragment要定义在查询之前:
# 定义仓库详情的Fragment,指定目标类型为GitHub的Repository fragment RepoDetails on Repository { name owner { login } description stargazerCount forkCount createdAt updatedAt primaryLanguage { name } } # 主查询直接引用Fragment query GetUserTopRepos($login: String!, $first: Int!) { user(login: $login) { repositories(first: $first, orderBy: {field: STARGAZERS, direction: DESC}) { nodes { ...RepoDetails } pageInfo { endCursor hasNextPage } } } }
多文件拆分写法
如果要把Fragment和查询分开存放,必须通过#import导入Fragment:
1. 单独的Fragment文件(fragments/RepoDetails.graphql)
fragment RepoDetails on Repository { name owner { login } description stargazerCount forkCount createdAt updatedAt primaryLanguage { name } }
2. 查询文件(queries/GetUserTopRepos.graphql)
# 导入同目录下fragments文件夹里的RepoDetails片段 #import "../fragments/RepoDetails.graphql" query GetUserTopRepos($login: String!, $first: Int!) { user(login: $login) { repositories(first: $first, orderBy: {field: STARGAZERS, direction: DESC}) { nodes { ...RepoDetails } pageInfo { endCursor hasNextPage } } } }
GraphQL Codegen 核心配置
确保你的codegen.ts配置能正确识别所有.graphql文件,包括Fragment文件:
import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { // 拉取GitHub官方GraphQL Schema,也可以本地存schema文件 schema: 'https://api.github.com/graphql', // 匹配所有src目录下的.graphql文件,包括子目录 documents: ['./src/**/*.graphql'], generates: { // 生成的TS文件路径 './src/generated/graphql.ts': { // 根据你的项目需求选择插件,这里是React项目常用组合 plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'], config: { skipTypename: false, withHooks: true, withComponent: false, }, }, }, ignoreNoDocuments: true, }; export default config;
常见失败原因排查
- Fragment类型不匹配:必须确保Fragment的
on Repository和GitHub GraphQL Schema中的类型完全一致(注意大小写,GitHub的仓库类型是首字母大写的Repository) - 多文件导入路径错误:
#import的路径要相对于当前查询文件的位置,路径写错会导致Codegen找不到Fragment - 配置未覆盖Fragment文件:
documents配置项要包含Fragment所在的文件夹,否则Codegen不会处理这些文件 - Schema版本不一致:如果本地用了旧的GitHub Schema,可能导致字段不匹配,建议直接用官方Schema地址拉取最新版本
内容的提问来源于stack exchange,提问作者DFBerry
相关产品推荐
相关产品推荐

