DEV Community

Tasfia Islam
Tasfia Islam

Posted on • Edited on

Using GraphQL Codegen with Typescript and urql

GraphQL codegen helps us to write queries, mutations, fragments and using hooks which are already typed.
read more about it

Assuming you already have urql , graphQL and typescript installed and setup in your project, (I am working on next.js project)
here is how you can install and use graphql codegen for typed variables throughout your project.

Installation



yarn add -D @graphql-codegen/typescript-urql 


Enter fullscreen mode Exit fullscreen mode

Add codegen CLI



yarn add -D @graphql-codegen/cli


Enter fullscreen mode Exit fullscreen mode

Initialize codegen configuration



yarn run graphql-codegen init


Enter fullscreen mode Exit fullscreen mode

This command will generate codegen configuration for you by asking for selecting your graphql endpoint, location of your graphql operation in the project, folder to write the output of codegen, script to run graphql codegen etc. You can also manually create the codegen.ts file and write the configuration there.

codegen config

Use your graphQL api endpoint as schema.
read more about config

Run

Run yarn install and the script you have set up to run codegen.
Eg. yarn run codegen

To run in watchmode,



yarn run codegen --watch


Enter fullscreen mode Exit fullscreen mode

Top comments (0)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay