DEV Community

Cristian Velasquez Ramos
Cristian Velasquez Ramos

Posted on • Originally published at cvr.im

1

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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay