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

如何用TypeScript为GraphQL查询响应添加类型定义?

解决Next.js+Shopify GraphQL的TypeScript类型自动生成问题

核心问题拆解

你遇到的本质问题是GraphQL Code Generator无法获取Shopify的GraphQL Schema,导致无法根据查询自动生成对应TS类型。手动编写类型在项目扩展时效率极低,下面是实操验证过的完整配置流程:

第一步:获取Shopify GraphQL Schema

Codegen必须依赖Schema才能生成类型,Shopify Storefront API的Schema可通过以下方式获取:

  • 方式一:Introspection命令导出(推荐)
    终端执行命令(替换你的店铺域名、Storefront Token和API版本):
    npx graphql-codegen introspect-schema https://{你的店铺域名}.myshopify.com/api/{API版本}/graphql.json \
      --header "X-Shopify-Storefront-Access-Token: {你的Storefront Token}" \
      --output schema.graphql
    
    执行成功后,项目根目录会生成schema.graphql文件,这就是Codegen需要的Schema源。
  • 方式二:使用官方Schema文件
    从Shopify开发者文档中找到对应API版本的Schema,复制保存为本地schema.graphql文件即可。

第二步:配置GraphQL Code Generator

  1. 安装依赖包:

    npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations
    

    (若使用Apollo客户端,可额外添加@graphql-codegen/typescript-react-apollo)

  2. 项目根目录创建codegen.ts配置文件:

    import type { CodegenConfig } from '@graphql-codegen/cli';
    
    const config: CodegenConfig = {
      schema: './schema.graphql', // 本地Schema文件路径
      documents: ['./src/graphql/**/*.graphql'], // 你的GraphQL查询文件存放路径
      generates: {
        './src/generated/graphql.ts': { // 生成的TS类型文件输出路径
          plugins: ['typescript', 'typescript-operations'],
          config: {
            skipTypename: true,
            enumsAsTypes: true,
          },
        },
      },
    };
    
    export default config;
    
  3. package.json中添加运行脚本:

    "scripts": {
      "codegen": "graphql-codegen --config codegen.ts"
    }
    

第三步:编写查询并生成类型

  1. 在src/graphql目录下创建查询文件,比如products.graphql:

    query GetProducts($first: Int!) {
      products(first: $first) {
        edges {
          node {
            id
            title
            priceRange {
              minVariantPrice {
                amount
                currencyCode
              }
            }
          }
        }
      }
    }
    
  2. 运行生成命令:

    npm run codegen
    

    执行成功后,src/generated/graphql.ts会自动生成GetProductsQuery、GetProductsQueryVariables等对应类型。

第四步:在Next.js中使用生成的类型

示例:在getServerSideProps中使用

import { GetProductsQuery } from '../generated/graphql';

export async function getServerSideProps() {
  const res = await fetch('https://{你的店铺域名}.myshopify.com/api/{API版本}/graphql.json', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-Shopify-Storefront-Access-Token': '{你的Storefront Token}',
    },
    body: JSON.stringify({
      query: `query GetProducts($first: Int!) { ... }`, // 或从文件导入查询字符串
      variables: { first: 10 },
    }),
  });

  const data = await res.json();
  // 断言数据类型为生成的查询类型
  const productsData = data.data as GetProductsQuery;

  return {
    props: { productsData },
  };
}

常见问题排查

  • 找不到Schema:检查schema路径是否正确,或Introspection命令是否生成了非空的schema.graphql文件。
  • 权限报错:确认Storefront Token拥有对应查询的权限(如读取产品),API版本不要使用已废弃的旧版本。
  • 查询文件不被识别:检查documents配置的路径是否匹配你的查询文件实际位置。

内容的提问来源于stack exchange,提问作者Prof.Chewbaccia

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 16:40:06