October 30, 2020 | 2 minutes read

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:

2┣ packages
3┃ ┣ api
4┃ ┃ ┣ src
5┃ ┃ ┃ ┣ index.ts
6┃ ┃ ┃ ┗ schema.gen.ts
7┃ ┃ ┗ codegen.yml
8┃ ┣ client
9┃ ┣ server

Here's how the api

file will look

1schema: http://localhost:4000/graphql
3 ./src/schema.gen.ts:
4 plugins:
5 - typescript

I add

to all generated files to make it easy to add in

The really cool part is when our server is running, any changes to the schema will automatically be tracked when running

1graphql-codegen --w
inside the api package.

Now all you have to do is import

from your client or server and you'll have access to all the typescript types.