DEV Community

Cristian Velasquez Ramos
Cristian Velasquez Ramos

Posted on • Originally published at cvr.im

GraphQL Code Generator in a monorepo

Disclaimer: this post assumes you have knowledge of how to setup a monorepo

Recently, I decided to use graphql-code-generator because I was tired of manually writing my schema definition and then writing the typescript types every single time.

With graphql-code-generator, I only have to write out the schema and the rest is, you probably guessed it, generated.

Using it within a monorepo allows you to make it so there's a single source of truth for all your API!

It will look a little something like this:

Diagram showing relation between the API and the monorepo packages

Let's map out our (basic) monorepo structure:

monorepo
 ┣ packages
 ┃ ┣ api 
 ┃ ┃ ┣ src
 ┃ ┃ ┃ ┣ index.ts 
 ┃ ┃ ┃ ┗ schema.gen.ts
 ┃ ┃ ┗ codegen.yml
 ┃ ┣ client
 ┃ ┣ server
Enter fullscreen mode Exit fullscreen mode

Here's how the api codegen.yml file will look

schema: http://localhost:4000/graphql
generates:
  ./src/schema.gen.ts:
    plugins:
      - typescript

Enter fullscreen mode Exit fullscreen mode

I add .gen. to all generated files to make it easy to add in .gitignore

The really cool part is when our server is running, any changes to the schema will automatically be tracked when running graphql-codegen --w inside the api package.

Now all you have to do is import @monorepo/api from your client or server and you'll have access to all the typescript types.

Top comments (0)