Frontend Serverless with React and GraphQL

Start at the beginning and work your way through this project. The code for each step as well as the finished project can be found in the Github repository.

13. Add GraphQLCodeGen type generation

Objective: Set up type generation based on our schema, queries and mutations.

We will use GraphQL Gen to generate the types for our data models that we will use across the Next Chop application. This tool will connect to our GraphCMS GraphQL backend and generate types based on the types of queries and mutations that we specified in the last step. The best part about this is that if we change our models in the future, we can re-run this and it will generate updated types based on the new schema, queries and mutations that we are executing against it.

First let's install all the libraries.


npm install --save @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations

Now we create the codegen.yml file that will specify where our backend and graphql files are. We also specify the plugins used, in our case we want to specify that we want typescript types created. There are all sorts of plugins available though including some that will even build Apollo fetching components. In our case though, we will simply use Apollo Hooks, which will make this even easier.


overwrite: true
documents: graphql/**/*.ts
- 'typescript'
- 'typescript-operations'

Next, we need to create an npm task that will make it easier to run our generate command. Add this to the package.json:


"generate": "gql-gen --config codegen.yml --require dotenv/config"

Now we can run this generate command.


npm run generate

This should produce apollo-components.tsx in the generated folder.