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项目)
- 安装依赖:
npm install @graphql-tools/webpack-loader graphql --save-dev
- 修改
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类型:
- 安装代码生成依赖:
npm install @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations --save-dev
- 创建
codegen.yml配置文件:
schema: "./src/schema.graphql" # 你的GraphQL Schema路径 documents: "./src/**/*.graphql" # 所有.graphql查询文件路径 generates: ./src/generated/graphql.ts: plugins: - "typescript" - "typescript-operations"
- 在
package.json添加生成脚本:
{ "scripts": { "generate-graphql": "graphql-codegen --config codegen.yml" } }
- 运行生成命令后,直接从生成文件导入查询:
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
相关产品推荐
相关产品推荐

