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

Next.js中GraphQL Code Generator未正确生成graphql()函数问题

GraphQL Code Generator 未正确生成类型的解决方法

我在Next.js项目中使用GraphQL并通过GraphQL Code Generator生成查询类型,但工具未正确生成代码。生成的gql.ts文件中提示**"The query argument is unknown! Please regenerate the types."**类型错误,错误截图如下:
GraphQL Codegen类型错误

当前使用的Code Generator配置:

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

const config: CodegenConfig = {
  schema:"http://localhost:4000/graphql",
  documents: ['components/**/*.tsx', 'app/**/*.tsx'],
  ignoreNoDocuments: true,
  generates:{
    './gql/':{
      preset:'client'
    }
  }
}

export default config

生成的gql.ts文件内容:

/* eslint-disable */
import * as types from './graphql';
import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core';

const documents = [];
/**
 * The graphql function is used to parse GraphQL queries into a document that can be used by GraphQL clients.
 *
 *
 * @example
 * ```ts
 * const query = graphql(`query GetUser($id: ID!) { user(id: $id) { name } }`);
 * ```
 *
 * The query argument is unknown!
 * Please regenerate the types.
 */
export function graphql(source: string): unknown;

export function graphql(source: string) {
  return (documents as any)[source] ?? {};
}

export type DocumentType<TDocumentNode extends DocumentNode<any, any>> = TDocumentNode extends DocumentNode<  infer TType,  any>  ? TType  : never;

尝试修改配置后问题仍未解决。


可能的解决方法

1. 确认项目中存在有效的GraphQL查询文档

Code Generator需要识别项目中的GraphQL查询/突变定义才能生成对应类型。检查components/**/*.tsx和app/**/*.tsx路径下是否有实际的GraphQL查询代码,比如:

// 示例查询,确保文件中有类似代码
import { graphql } from '../gql';

const GET_POSTS = graphql(`
  query GetPosts {
    posts {
      id
      title
    }
  }
`);

如果没有任何查询文档,工具会生成空的模板代码,就会出现上述错误。

2. 检查文档路径匹配是否正确

确认documents配置的路径能覆盖到所有包含GraphQL查询的文件:

  • 如果使用Next.js App Router,可能需要调整路径为app/**/*.{tsx,ts}
  • 若查询存在于其他目录(如lib/),需要添加对应路径到documents数组中

3. 禁用ignoreNoDocuments配置

当前配置中ignoreNoDocuments: true会让工具在未找到文档时不报错,但会生成空模板。将其改为false,运行生成命令时会明确提示是否找到文档,方便排查:

const config: CodegenConfig = {
  // ...其他配置
  ignoreNoDocuments: false,
  // ...
}

4. 手动指定预设的额外配置

使用client预设时,可以添加presetConfig确保类型正确生成:

generates:{
  './gql/':{
    preset:'client',
    presetConfig: {
      gqlTagName: 'graphql' // 确保和项目中使用的标签名一致
    }
  }
}

5. 清理缓存并重新生成

执行以下命令清理缓存并重新运行生成:

rm -rf node_modules/.cache/graphql-codegen
npx graphql-codegen

6. 检查Schema是否可正常访问

确认schema配置的http://localhost:4000/graphql服务正在运行,且能正常返回Schema。可以通过访问该URL在浏览器中查看GraphQL Playground,确保Schema可用。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 11:32:46