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

如何配置graphql-codegen生成嵌套对象独立类型?

配置graphql-codegen生成独立嵌套对象类型

可以通过typescript-operations插件的配置参数实现你想要的类型生成方式,具体操作如下:

在你的代码生成配置文件(如codegen.yml或codegen.ts)中,为typescript-operations插件添加以下关键配置项:

  • preResolveTypes: false:关闭预解析类型功能,避免嵌套对象被直接内联到主查询类型中
  • exportFragmentSpreadSubTypes: true:强制导出所有嵌套的子对象类型

示例配置(codegen.yml)

schema: "./schema.graphql"
documents: "./src/**/*.graphql"
generates:
  ./src/generated/graphql.ts:
    plugins:
      - typescript
      - typescript-operations
    config:
      preResolveTypes: false
      exportFragmentSpreadSubTypes: true

执行代码生成命令后,针对你提供的MyData查询,会生成类似这样的独立类型:

export type MyDataQueryViewer = {
  __typename: 'Viewer';
  id: number;
  username: string;
}

export type MyDataQuery = {
  __typename: 'Query';
  viewer?: MyDataQueryViewer;
}

如果需要和Apollo codegen完全一致的下划线分隔命名(如MyDataQuery_viewer),可以通过namingConvention自定义命名规则。由于YAML配置不支持函数,需要改用codegen.ts格式的配置文件,示例如下:

import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: ['./src/**/*.graphql'],
  generates: {
    './src/generated/graphql.ts': {
      plugins: ['typescript', 'typescript-operations'],
      config: {
        preResolveTypes: false,
        exportFragmentSpreadSubTypes: true,
        namingConvention: {
          typeNames: (typeName: string) => {
            // 将驼峰命名转换为下划线分隔格式,比如 MyDataQueryViewer → MyDataQuery_viewer
            return typeName.replace(/(?<=Query)([A-Z])/g, '_$1');
          },
        },
      },
    },
  },
};

export default config;

注意:请确保使用@graphql-codegen/typescript-operations的最新稳定版本,这些配置项在旧版本中可能未实现。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 17:57:27