October 30, 2020 | 2 minutes read
GraphQL Code Generator in a monorepo
#graphql#monorepo#devops
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:
Let's map out our (basic) monorepo structure:
1monorepo2┣ packages3┃ ┣ api4┃ ┃ ┣ src5┃ ┃ ┃ ┣ index.ts6┃ ┃ ┃ ┗ schema.gen.ts7┃ ┃ ┗ codegen.yml8┃ ┣ client9┃ ┣ server
Here's how the api
file will look1codegen.yml
1schema: http://localhost:4000/graphql2generates:3 ./src/schema.gen.ts:4 plugins:5 - typescript
I add
to all generated files to make it easy to add in1.gen.1.gitignore
The really cool part is when our server is running, any changes to the schema will automatically be tracked when running
inside the api package.1graphql-codegen --w
Now all you have to do is import
from your client or server and you'll have access to all the typescript types.1@monorepo/api