본문 바로가기
개발일지

vite react typescript + graphql code generator 적용하기

by 케이오스 2023. 1. 3.

1. vite 설치

2. apollo-client 설치

3. graphql-code-generator 설치

4. 코드 수정

 

# 1. vite 설치

$npm create vite@latest

# 2. apollo-client 설치

$npm install @apollo/client graphql

# 3. graphql-code-generator 설치 

$npm install -D @graphql-codegen/cli

import React from 'react';
import * as ReactDOM from 'react-dom/client';
import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';
import App from './App';

const client = new ApolloClient({
    uri: 'https://flyby-gateway.herokuapp.com/',
    cache: new InMemoryCache(),
}); // Supported in React 18+

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
    <ApolloProvider client={client}>
        <App />
    </ApolloProvider>
);

const GET_LOCATIONS = gql`
    query GetLocations {
        locations {
            id
            name
            description
            photo
        }
} `;

function DisplayLocations() {
    const { loading, error, data } = useQuery<"자동생성 타입 입력">(GET_LOCATIONS);
    if (loading) return <p>Loading...</p>;
    if (error) return <p>Error : {error.message}</p>;
    return data.locations.map(({ id, name, description, photo }) => (
        <div key={id}>
            <h3>{name}</h3>
            <img width="400" height="250" alt="location-reference" src={`${photo}`} />
            <br />
            <b>About this location:</b>
            <p>{description}</p>
            <br />
        </div>
    ));
}

$npx graphql-code-generator init
$npm install
# install the chosen packages
Welcome to GraphQL Code Generator!
Answer few questions and we will setup everything for you. ?
What type of application are you building? Application built with React
? Where is your schema?: (path or url) http://localhost:4000/graphql
? Where are your operations and fragments?: src/**/*.tsx
? Where to write the output: src/gql // #<-- 주의
? Do you want to generate an introspection file? No
? How to name the config file? codegen.ts
? What script in package.json should run the codegen? codegen

$npm run codegen

오류나면,
# package.json
"type": "module" 라인 삭제,

# 4. 코드 수정

# codegen.ts
"src/gql" -> "src/gql/" 로 변경 "/" 추가
generates: {
    "src/gql/": {
        preset: "client",
        plugins: [],
    },
},