将graphql-codegen查询移至独立文件时出现运行时错误
解决独立GraphQL查询文件导入报错问题
核心原因
报错是因为独立文件中的查询未被正确转换为GraphQL DocumentNode类型——要么是没使用gql标签解析查询,要么是构建工具/代码生成配置未覆盖这些独立文件。
具体解决步骤
正确编写独立查询文件
在查询文件(比如src/graphql/queries/pollQueries.ts)中,必须用gql标签包裹查询并正确导出:// 若使用Apollo Client,从@apollo/client导入gql;否则安装graphql-tag包后导入 import { gql } from '@apollo/client'; export const POLL_SET = gql` query PollSet { polls { id title options { label votes } } } `;更新graphql-codegen配置
确保代码生成工具能识别你的独立查询文件,修改codegen.ts配置:import type { CodegenConfig } from '@graphql-codegen/cli'; const config: CodegenConfig = { schema: './src/graphql/schema.graphql', // 你的schema文件路径 documents: ['./src/graphql/queries/**/*.ts'], // 匹配所有独立查询文件 generates: { './src/generated/graphql.ts': { plugins: ['typescript', 'typescript-operations', 'typescript-react-apollo'], }, }, }; export default config;之后重新执行代码生成命令:
npx graphql-codegen配置构建工具处理gql标签
根据你使用的构建工具做对应配置:- Webpack:安装
babel-plugin-graphql-tag并添加到babel配置:
若使用{ "plugins": ["babel-plugin-graphql-tag"] }.graphql后缀的纯查询文件,需添加graphql-tag/loader到webpack配置:module.exports = { module: { rules: [ { test: /\.(graphql|gql)$/, exclude: /node_modules/, loader: 'graphql-tag/loader', }, ], }, }; - Vite:安装
vite-plugin-graphql并配置vite.config.ts:import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; import graphql from 'vite-plugin-graphql'; export default defineConfig({ plugins: [react(), graphql()], });
- Webpack:安装
检查导入方式
在组件中直接导入导出的查询常量即可:import { POLL_SET } from './graphql/queries/pollQueries'; // 在组件中使用,比如配合useQuery const { data } = useQuery(POLL_SET);
内容的提问来源于stack exchange,提问作者jcubic
相关产品推荐
相关产品推荐

