⬡ GraphQL Advanced

What is the GraphQL Codegen tool and how is it used?

Answer

GraphQL Code Generator (graphql-codegen by The Guild) automatically generates TypeScript types, React hooks, resolvers, and more from your GraphQL schema and operations. Setup: npm install -D @graphql-codegen/cli @graphql-codegen/typescript. Configure codegen.yml: schema: http://localhost:4000/graphql documents: src/**/*.graphql generates: src/generated/graphql.ts: plugins: [typescript, typescript-operations, typescript-react-apollo]. Running graphql-codegen generates: TypeScript interfaces for all schema types, typed operation hooks (useGetUsersQuery), typed resolvers for the server. Benefits: (1) End-to-end type safety: client operations match server schema at compile time. (2) Auto-complete: IDE knows the shape of query results. (3) Catch schema drift: codegen fails if operations reference deleted fields. (4) Reduced boilerplate: no manual type writing. Run in watch mode during development: graphql-codegen --watch.