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:
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
codegen.yml file will look
1schema: http://localhost:4000/graphql2generates:3 ./src/schema.gen.ts:4 plugins:5 - typescript
.gen.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
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.