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

NestJS(TypeScript)中Apollo Client加载.graphql为DocumentNode的配置问题

解决NestJS中导入.graphql文件的类型错误问题

步骤1:确保类型声明文件被TypeScript识别

你的graphql.d.ts声明文件未被TypeScript扫描到,按以下调整:

  • 将graphql.d.ts放在项目根目录或src目录下
  • 修改tsconfig.json,在include数组中添加该文件路径:
{
  "compilerOptions": {
    // 保留原有配置
  },
  "include": [
    "src/**/*",
    "graphql.d.ts" // 若文件在src内则改为"src/graphql.d.ts"
  ]
}

步骤2:添加GraphQL文件加载器

TypeScript原生不支持解析.graphql文件,需添加加载器处理:

方案A:使用webpack loader(适配webpack构建的NestJS项目)

  1. 安装依赖:
npm install @graphql-tools/webpack-loader graphql --save-dev
  1. 修改webpack.config.js(若无则新建):
module.exports = {
  module: {
    rules: [
      {
        test: /\.graphql$/,
        exclude: /node_modules/,
        use: {
          loader: '@graphql-tools/webpack-loader',
        },
      },
    ],
  },
};

方案B:使用NestJS GraphQL代码生成(更贴合Nest生态)

若已使用@nestjs/graphql,可通过代码生成自动生成DocumentNode类型:

  1. 安装代码生成依赖:
npm install @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations --save-dev
  1. 创建codegen.yml配置文件:
schema: "./src/schema.graphql" # 你的GraphQL Schema路径
documents: "./src/**/*.graphql" # 所有.graphql查询文件路径
generates:
  ./src/generated/graphql.ts:
    plugins:
      - "typescript"
      - "typescript-operations"
  1. 在package.json添加生成脚本:
{
  "scripts": {
    "generate-graphql": "graphql-codegen --config codegen.yml"
  }
}
  1. 运行生成命令后,直接从生成文件导入查询:
npm run generate-graphql
import { ExampleQuery } from './generated/graphql';

this.apolloClient.query({
  query: ExampleQuery,
});

步骤3:验证导入路径

确保导入.graphql文件时路径正确,例如文件在src/graphql/example.graphql,导入语句应为:

import example from './graphql/example.graphql';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 13:57:31