본문 바로가기

React

React 앱에 GraphQL Code Generator 적용하기

React 프로젝트에서 GraphQL API를 사용할 때, 타입 정의를 일일이 작성하면 번거롭고 실수가 발생하기 쉽습니다. GraphQL Code Generator를 활용하면 스키마와 쿼리로부터 타입‑안전한 API 클라이언트를 자동으로 생성할 수 있습니다. 이번 포스트에서는 Create React App(또는 Vite) 기반 프로젝트에 GraphQL Code Generator를 도입하고, 자동 생성된 타입을 활용해 React 컴포넌트를 작성하는 방법을 단계별로 설명합니다.

1. 프로젝트 초기 설정

먼저 React 앱을 생성하고, Apollo Client와 GraphQL 의존성을 설치합니다.

npx create-react-app graphql-codegen-demo --template typescript
cd graphql-codegen-demo
npm install @apollo/client graphql

위 명령으로 TypeScript 기반 React 프로젝트와 Apollo Client를 준비합니다.

2. GraphQL Code Generator 설치

다음 패키지를 개발 의존성으로 추가합니다.

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

설치가 완료되면 프로젝트 루트에 codegen.yml 설정 파일을 생성합니다.

3. codegen.yml 설정

schema: "https://countries.trevorblades.com/"
# 혹은 로컬 스키마 파일: ./src/schema.graphql
documents: "src/**/*.graphql"
generates:
  src/generated/graphql.tsx:
    plugins:
      - "typescript"
      - "typescript-operations"
      - "typescript-react-apollo"
    config:
      withHooks: true
      reactApolloVersion: 3

위 설정은 src/**/*.graphql 경로에 있는 모든 GraphQL 쿼리·뮤테이션 파일을 읽어, src/generated/graphql.tsx에 타입 정의와 React Hook을 자동 생성하도록 합니다.

4. GraphQL 쿼리 파일 만들기

예시로 국가 정보를 조회하는 쿼리를 작성해 보겠습니다.

# src/queries/GetCountries.graphql
query GetCountries {
  countries {
    code
    name
    emoji
  }
}

이 파일을 저장하면 codegen.yml에 정의된 경로에 맞춰 자동으로 타입이 생성됩니다.

5. 코드 자동 생성 실행

npx graphql-codegen

실행 후 src/generated/graphql.tsx 파일이 생성되고, 다음과 같은 내용이 포함됩니다.

export type GetCountriesQueryVariables = Exact<{}>;
export type GetCountriesQuery = { __typename?: 'Query', countries: Array<{ __typename?: 'Country', code: string, name: string, emoji: string }> };

export const GetCountriesDocument = gql`
  query GetCountries {
    countries {
      code
      name
      emoji
    }
  }
`;

export function useGetCountriesQuery(baseOptions?: Apollo.QueryHookOptions<GetCountriesQuery, GetCountriesQueryVariables>) {
  return Apollo.useQuery<GetCountriesQuery, GetCountriesQueryVariables>(GetCountriesDocument, baseOptions);
}

이제 컴포넌트에서 useGetCountriesQuery 훅을 타입‑안전하게 사용할 수 있습니다.

6. React 컴포넌트에 적용

import React from 'react';
import { useGetCountriesQuery } from './generated/graphql';

const CountryList: React.FC = () => {
  const { data, loading, error } = useGetCountriesQuery();

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {data?.countries.map((c) => (
        <li key={c.code}>
          {c.emoji} {c.name} ({c.code})
        </li>
      ))}
    </ul>
  );
};

export default CountryList;

위 코드에서 data?.countries는 자동 생성된 타입 덕분에 code, name, emoji가 존재한다는 것을 컴파일 타임에 보장합니다.

7. 개발 편의성 자동화

코드 변경 시마다 수동으로 graphql-codegen을 실행하는 대신, package.json에 스크립트를 추가해 개발 서버와 동시에 타입을 재생성하도록 할 수 있습니다.

"scripts": {
  "start": "react-scripts start",
  "codegen": "graphql-codegen --watch",
  "dev": "npm-run-all --parallel start codegen"
}

npm run dev를 실행하면 React 개발 서버와 코드젠 워처가 동시에 동작해, 쿼리 파일을 수정할 때마다 자동으로 타입이 업데이트됩니다.

8. 배포 시 정적 타입 포함

빌드 단계에서 npm run codegen을 한 번 실행하고, src/generated 폴더를 프로젝트에 커밋해두면 CI/CD 파이프라인에서도 타입 오류를 사전에 차단할 수 있습니다.

이제 GraphQL Code Generator를 활용해 React 앱에서 타입‑안전한 API 클라이언트를 자동으로 생성하고, 개발 생산성을 크게 향상시킬 수 있습니다.