You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过本地.gql文件配置graphql-codegen生成目标代码?

基于本地.gql文件使用graphql-codegen生成代码的正确配置

你的配置文件存在语法错误,这是导致yarn codegen运行失败的核心原因。以下是修正后的完整配置和关键注意事项:

修正后的codegen.yml配置

overwrite: true
# 正确指定本地schema文件路径,确保文件与codegen.yml在同一目录,或使用正确的相对/绝对路径
schema: './localfile.gql'
documents: ./*.{ts,tsx}
generates:
  types/generated/introspection.graphql:
    plugins:
      - schema-ast
    config:
      sort: true
  types/generated/graphql.tsx:
    config:
      # TypeScript基础配置
      declarationKind: 'interface'
      scalars:
        DateTime: string
        ID: string
      namingConvention:
        enumValues: change-case#upperCase
      avoidOptionals:
        field: true
      # 操作相关配置
      skipTypename: true
      # React Apollo钩子配置
      withHooks: true
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo

关键检查与操作步骤

  1. 补全依赖安装
    确保已安装所有必需的插件和工具包,执行命令:

    yarn add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo @graphql-codegen/schema-ast change-case
    

    (change-case是配置中enumValues指定的枚举转换工具,必须安装)

  2. 验证文件路径

    • 确认localfile.gql存在于指定路径下,若文件在子目录中,需调整schema字段路径(如./schemas/localfile.gql)
    • 若项目中GraphQL操作文件分布在子目录,可修改documents字段为./src/**/*.{ts,tsx}以覆盖所有相关文件
  3. 执行代码生成
    运行命令触发生成:

    yarn codegen
    

常见问题排查

  • 若仍报错,检查localfile.gql本身的语法是否合法(比如是否存在未闭合的定义、语法拼写错误)
  • 若提示插件找不到,确认所有@graphql-codegen/*相关依赖的版本与@graphql-codegen/cli版本一致,避免版本不兼容问题

内容的提问来源于stack exchange,提问作者K Pisco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 04:31:03