Token导航 LogoToken导航TokenDH.com
研究检索external-servicegithub未标认证来源可访问许可证需确认审计通过

graphql-codegenGraphQL codegen 文档

Agent Skill

用于辅助 API 设计、接口文档、请求响应结构和服务集成说明。它适合让 Agent 梳理 endpoint、生成 OpenAPI 草稿、检查字段命名、整理错误码或辅助前后端联调。使用时需要确认真实业务语义、鉴权方式、分页和错误处理规则;涉及生成接口文档时,应避免凭空补字段,最好从现有代码、schema 或接口样例中提取事实。

总安装

605

周安装

26

GitHub Stars

12

下载量

212
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:graphql-codegen(GraphQL codegen 文档)
来源仓库:https://github.com/claude-dev-suite/claude-dev-suite
仓库路径:skills/graphql-codegen
安装命令:
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill graphql-codegen
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill graphql-codegen

简介

用于 GraphQL 客户端代码自动生成,提升开发效率。

  • 支持 TypeScript 类型安全、查询片段复用与缓存策略。
  • 集成 Apollo Client 与 urql 等多框架预设配置。
  • schema 变更时应同步更新 codegen 配置,避免类型断裂。
  • graphql-codegen 属于研究检索类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

GraphQL Code Generator Core Knowledge

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: graphql-codegen for comprehensive documentation.

Installation

npm install -D @graphql-codegen/cli @graphql-codegen/typescript \
  @graphql-codegen/typescript-operations @graphql-codegen/client-preset

Basic Configuration

// codegen.ts
import type { CodegenConfig } from '@graphql-codegen/cli';

const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: ['src/**/*.tsx', 'src/**/*.ts'],
  ignoreNoDocuments: true,
  generates: {
    './src/gql/': {
      preset: 'client',
      config: {
        documentMode: 'string',
      },
    },
  },
};

export default config;

Run Generation

npx graphql-codegen
npx graphql-codegen --watch  # Watch mode

Client Preset (Recommended)

The client preset generates everything needed for type-safe GraphQL.

// codegen.ts
const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: ['src/**/*.tsx'],
  generates: {
    './src/gql/': {
      preset: 'client',
      plugins: [],
      presetConfig: {
        gqlTagName: 'gql',
        fragmentMasking: { unmaskFunctionName: 'getFragmentData' },
      },
    },
  },
};

Usage

import { gql } from '../gql';
import { useQuery } from '@apollo/client';

const GET_USER = gql(`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      name
      email
    }
  }
`);

function UserProfile({ id }: { id: string }) {
  const { data, loading } = useQuery(GET_USER, {
    variables: { id },
  });

  if (loading) return <Spinner />;
  // data.user is fully typed
  return <div>{data?.user?.name}</div>;
}

TanStack Query Integration

npm install -D @graphql-codegen/typescript-react-query
// codegen.ts
const config: CodegenConfig = {
  schema: 'http://localhost:4000/graphql',
  documents: ['src/**/*.graphql'],
  generates: {
    './src/gql/index.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-react-query',
      ],
      config: {
        fetcher: {
          func: './fetcher#fetcher',
          isReactHook: false,
        },
        reactQueryVersion: 5,
        addInfiniteQuery: true,
      },
    },
  },
};

Fetcher

// src/gql/fetcher.ts
export const fetcher = <TData, TVariables>(
  query: string,
  variables?: TVariables
): (() => Promise<TData>) => {
  return async () => {
    const response = await fetch('http://localhost:4000/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${getToken()}`,
      },
      body: JSON.stringify({ query, variables }),
    });

    const json = await response.json();
    if (json.errors) {
      throw new Error(json.errors[0].message);
    }
    return json.data;
  };
};

Generated Hooks Usage

import { useGetUserQuery, useCreateUserMutation } from './gql';

function UserProfile({ id }: { id: string }) {
  const { data, isLoading } = useGetUserQuery({ id });
  const createMutation = useCreateUserMutation();

  const handleCreate = () => {
    createMutation.mutate({
      input: { name: 'John', email: 'john@example.com' },
    });
  };

  if (isLoading) return <Spinner />;
  return <div>{data?.user?.name}</div>;
}

Fragment Colocation

// components/UserAvatar.tsx
import { gql, FragmentType, getFragmentData } from '../gql';

export const USER_AVATAR_FRAGMENT = gql(`
  fragment UserAvatar on User {
    id
    name
    avatarUrl
  }
`);

interface Props {
  user: FragmentType<typeof USER_AVATAR_FRAGMENT>;
}

export function UserAvatar({ user }: Props) {
  const data = getFragmentData(USER_AVATAR_FRAGMENT, user);
  return <img src={data.avatarUrl} alt={data.name} />;
}

// Usage in parent query
const GET_USER = gql(`
  query GetUser($id: ID!) {
    user(id: $id) {
      id
      ...UserAvatar
    }
  }
`);

Production Readiness

Schema Polling

// codegen.ts
const config: CodegenConfig = {
  schema: [
    {
      'http://localhost:4000/graphql': {
        headers: {
          Authorization: `Bearer ${process.env.GRAPHQL_TOKEN}`,
        },
      },
    },
  ],
  // ...
};

Multiple Schemas

const config: CodegenConfig = {
  generates: {
    './src/gql/user-api/': {
      schema: 'http://user-api:4000/graphql',
      documents: ['src/features/user/**/*.tsx'],
      preset: 'client',
    },
    './src/gql/product-api/': {
      schema: 'http://product-api:4001/graphql',
      documents: ['src/features/product/**/*.tsx'],
      preset: 'client',
    },
  },
};

CI/CD Integration

# .github/workflows/codegen.yml
name: GraphQL Codegen

on:
  push:
    paths:
      - 'src/**/*.graphql'
      - 'src/**/*.tsx'

jobs:
  generate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: npm ci
      - run: npx graphql-codegen
      - name: Check for changes
        run: |
          if [[ -n $(git status --porcelain src/gql) ]]; then
            echo "Generated files changed"
            exit 1
          fi

Package Scripts

{
  "scripts": {
    "codegen": "graphql-codegen",
    "codegen:watch": "graphql-codegen --watch"
  }
}

Checklist

  • Schema source configured (URL or local)
  • Documents path matches source files
  • Client preset for optimal output
  • Fetcher configured with auth
  • Fragment colocation pattern
  • Watch mode for development
  • CI validation of generated code
  • TypeScript strict mode compatible

When NOT to Use This Skill

  • REST API type generation (use openapi-codegen skill)
  • tRPC type-safe APIs (use trpc skill)
  • GraphQL schema design (use graphql skill)
  • Non-TypeScript projects
  • Simple GraphQL queries without type generation needs

Anti-Patterns

Anti-PatternWhy It's BadSolution
Committing generated files to gitMerge conflicts, outdated typesAdd to.gitignore, generate in CI
Not using client presetVerbose configurationUse client preset for modern setup
Ignoring schema changesType mismatches at runtimeRun codegen in watch mode during dev
Missing operationId or query namesPoor generated hook namesName all queries/mutations
Not using fragmentsCode duplicationUse fragments for reusable fields
Generating types onlyMissing runtime validationCombine with schema validation
Hardcoding schema URLEnvironment couplingUse env variables for schema source
Not versioning generator packagesInconsistent output across teamPin generator versions

Quick Troubleshooting

IssuePossible CauseSolution
Generation failsInvalid schema or documentsValidate schema, check GraphQL syntax
Type errors after generationSchema/code mismatchRegenerate types, check schema changes
Missing typesDocuments path not matching filesCheck documents glob pattern
Duplicate operation namesSame query name in multiple filesUse unique operation names
Fragment not foundFragment not in documentsInclude fragment file in documents
Hook not generatedNot using React Query pluginAdd typescript-react-query plugin
"Cannot find module './gql'"Generation didn't runRun npm run codegen
Slow generationToo many documentsOptimize glob patterns, use ignoreNoDocuments
Type inference not workingWrong import pathImport from generated gql folder

Reference Documentation

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude

32.18%
按下载量换算68

Codex

30.95%
按下载量换算66

Cursor

19.36%
按下载量换算41

Gemini CLI

9.39%
按下载量换算20

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

external-service

该 Skill 可能调用第三方服务、云服务或外部模型 API,使用前需要确认账号、额度、数据发送范围和服务条款。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills