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

Next.js中Graphql Codegen Document重复定义错误的解决方法

解决GraphQL Codegen重复定义及插件验证问题

一、修复name 'MySomeDocument' is defined multiple times错误

这个问题的核心是两个GraphQL Schema生成的类型文件产生了命名冲突,解决思路是将不同Schema的生成结果隔离:

1. 为每个Schema单独生成独立的类型文件

修改你的GraphQL Codegen配置文件,在generates字段中为每个Schema指定单独的输出文件,避免内容合并导致的重复定义。示例配置(以YAML格式为例):

schema:
  - https://your-first-schema-url.com/graphql
  - https://your-second-schema-url.com/graphql
documents: "./utils/graphql/*.ts"
generates:
  # 第一个Schema的类型输出
  ./utils/generated/schema1-types.ts:
    schema: https://your-first-schema-url.com/graphql
    preset: client
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
  # 第二个Schema的类型输出
  ./utils/generated/schema2-types.ts:
    schema: https://your-second-schema-url.com/graphql
    preset: client
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
  # 保留schema.json生成
  ./utils/generated/graphql.schema.json:
    plugins:
      - introspection

这样两个Schema的类型会分别输出到不同文件,不会出现同名变量冲突。

2. 检查并修正文档中的重复操作名

排查./utils/graphql/*.ts中的GraphQL查询/突变定义,确保没有跨Schema使用相同的操作名(比如两个不同的查询都命名为MySomeQuery),如果有,给操作名加上Schema相关前缀(如Schema1_MySomeQuery)来区分。

二、修复移除client预设后的插件验证错误

typescript-react-apollo插件依赖正确的文件扩展名配置,client预设会自动处理这个配置,手动移除后需要显式指定:

schema: [你的两个Schema地址]
documents: "./utils/graphql/*.ts"
generates:
  ./utils/generated/types.ts:
    plugins:
      - typescript
      - typescript-operations
      - typescript-react-apollo
    config:
      extension: .ts # 显式指定文件扩展名,满足插件要求
  ./utils/generated/graphql.schema.json:
    plugins:
      - introspection

不过更推荐保留client预设,它会帮你处理很多默认配置(比如文件拆分、扩展名、类型导出规范等),减少手动配置的潜在问题。

三、额外检查

确认Next.js项目中导入生成类型时,路径指向的是正确的隔离文件,没有同时导入两个Schema生成的同名类型。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 02:02:10