如何配置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
相关产品推荐
相关产品推荐

