React + GraphQL에 Codegen 적용

minidoo·2026년 4월 24일

GraphQL

목록 보기
5/5

🔔 GraphQL 백엔드 서버의 스키마를 가져와 타입을 생성할 수 있다: Codegen

1. Codegen 설치

$ yarn add --dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
  • @graphql-codegen/typescript: GraphQL 스키마 타입을 TypeScript로 생성
  • @graphql-codegen/typescript-operations: GraphQL 쿼리 및 뮤테이션에 대한 타입 생성
  • @graphql-codegen/typescript-react-apollo: 생성된 GraphQL 쿼리를 React에서 사용할 수 있는 훅으로 변환

2. 쿼리 및 뮤테이션 작성

query Users {
  getUsers {
    name
    email
  }
}

3. Codegen 설정 파일 작성

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "http://localhost:4000/graphql", // 백엔드 GraphQL 엔드포인트
  documents: "src/**/*.graphql", // GraphQL 쿼리 및 뮤테이션 문서 위치
  generates: {
    "src/graphql/generated.ts": {
      plugins: [
        "typescript",
        "typescript-operations",
        "typescript-react-apollo",
      ],
    },
  },
  hooks: {
    afterAllFileWrite: ["prettier --write"],
  },
};

export default config;

4. 실행 스크립트 작성

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

yarn codegen 명령어를 통해 실행하면 src/graphql/generated.ts 파일에 스키마, 쿼리 및 뮤테이션 타입, React Hook이 자동 생성된다. (서버에서 가져옴)

✨ client-preset 사용법

참고: https://the-guild.dev/graphql/codegen/plugins/presets/preset-client

typescript, typescript-operation 플러그인 문서를 보면 client-preset을 추천한다.

$ yarn remove @graphql-codegen/typescript @graphql-codegen/typescript-operations
$ yarn add --dev @graphql-codegen/client-preset
import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: "http://localhost:4000/graphql",
  documents: "src/**/*.graphql",
  generates: {
    "./src/gql/": {
      preset: "client",
      plugins: ["typescript-react-apollo"],
      presetConfig: {
        fragmentMasking: false,
      },
    },
  },
  hooks: {
    afterAllFileWrite: ["prettier --write"],
  },
};

export default config;

yarn codegen 명령어를 통해 실행하면 src/gql/graphql.ts 파일에 스키마, 쿼리 및 뮤테이션 타입, React Hook이 자동 생성된다.

import { useUsersQuery } from '../gql/graphql.ts';

export const HomePage = () => {
	const { data, loading, error } = useUsersQuery();
	return <></>;
}

0개의 댓글