GraphQL Typegen
Examples
Introduction
If you’re already using Gatsby with TypeScript and manually typing the results of your queries, you’ll learn in this guide how Gatsby’s automatic GraphQL Typegen feature can make your life easier. By relying on the types that are generated by Gatsby itself and using autocompletion for GraphQL queries in your IDE you’ll be able to write GraphQL queries quicker and safer.
This feature was added in gatsby@4.15.0. By default, this feature is only generating files during gatsby develop.
Prerequisites
A Gatsby project set up with
gatsby@4.15.0or later.The config option
graphqlTypegenset totrueinsidegatsby-config.A
tsconfig.jsonin your project with"include": ["./src/**/*"]set. See fulltsconfig.jsonexample.Optional: If you use VSCode you may install the GraphQL extension.
Using the autogenerated Queries types
For this example to work you’ll have to have a title inside your siteMetadata (in gatsby-config).
Start the development server with
gatsby develop. Once the server is ready you should see a log messageGenerating GraphQL and TypeScript typesat the bottom of your terminal.Gatsby created a type generation file which you should see at
src/gatsby-types.d.ts. It contains the TypeScript types for your queries. Yourtsconfig.jsonshould include this file so that you can access thenamespace Querieseverywhere in your project.Create a new page at
src/pages/typegen.tsxwith the following contents:It is important that your query has a name (here:
query TypegenPage {}) as otherwise the automatic type generation doesn’t work. We recommend naming the query the same as your React component and using PascalCase. You can enforce this requirement by usinggraphql-eslint.Access the
Queriesnamespace and use theTypegenPageQuerytype in your React component like so:When you type out the site title like this you should get TypeScript IntelliSense:
Configuring the gatsby-config option
Instead of setting a boolean value for the graphqlTypegen option in gatsby-config you can also set an object to configure it. See all details in the gatsby-config documentation.
- With
typesOutputPaththe output path can be specified. Make sure to also update the"include"setting in yourtsconfig.jsonto include the new path. - With
documentSearchPathsit’s possible to overwrite the search path for the documents, which are scanned for GraphQL queries.
Non-Nullable types
As Gatsby infers all fields — unless an explicit schema by the user is provided — they are nullable by default. For GraphQL Typegen this means that fields are possibly null. You can see this in the example above where you had to type data.site?.siteMetadata?.title as both siteMetadata and title are nullable.
If you’re sure that siteMetadata.title is always available you can use Gatsby’s schema customization API to explicitly type your fields:
Read the Customizing the GraphQL schema guide to learn how to explicitly define types in your site or source plugin.
GraphQL fragments
Fragments allow you to reuse parts of GraphQL queries throughout your site and collocate specific parts of a query to individual files. Learn more about it in the Using GraphQL fragments guide.
In the context of GraphQL Typegen fragments enable you to have individual TypeScript types for nested parts of your queries since each fragment will be its own TypeScript type. You then can use these types to e.g. type arguments of components consuming the GraphQL data.
Here’s an example (also used in using-graphql-typegen) with a Info component that gets the buildTime as an argument. This Info component and its SiteInformation fragment is used in the src/pages/index.tsx file then:
This way a SiteInformationFragment TypeScript type will be created that you can use in the Info component:
Tips
- When adding a new key to your GraphQL query you’ll need to save the file before new TypeScript types are generated. The autogenerated files are only updated on file saves.
- When using
gatsby-plugin-image(and Image CDN) you’ll get the correct TypeScript types forgatsbyImageDataandgatsbyImageautomatically. - We recommend adding
src/gatsby-types.d.tsto your.gitignoreas it’s machine generated code and duplicated information that is already existent in e.g. your page queries.
Configuring the VSCode GraphQL plugin
Install the GraphQL extension in your VSCode.
Create a
graphql.config.jsat the root of your project with the following contents:The VSCode extension will pick up the
graphql.config.jsfile and use the autogenerated file from Gatsby’s.cachedirectory. To learn more aboutgraphql.config.jshead to the GraphQL Config documentation.Restart VSCode so that the GraphQL extension takes effect.
Start the development server with
gatsby develop.Go to any of your queries, e.g. a page query inside
src/pagesand use Ctrl + Space (or use Shift + Space as an alternate keyboard shortcut) to get autocompletion like in GraphiQL.
Multiple GraphQL projects
If your repository has multiple GraphQL projects including Gatsby, you can configure it with the projects key:
Subdirectory
If your Gatsby project is in a subdirectory, e.g. site your config should look like this:
graphql-eslint
You can optionally use graphql-eslint to lint your GraphQL queries. It seamlessly integrates with the graphql.config.js file you created in the other step.
This guide assumes that you don’t have any existing ESLint configuration yet. You’ll need to adapt your configuration if you’re already using ESLint and refer to graphql-eslint’s documentation.
Install dependencies
Edit your
package.jsonto add two scripts:Create a
.eslintrc.jsfile to configure ESLint:Create a
graphql.config.jsat the root of your project with the following contents:Start the Gatsby development server with
gatsby developand check that.cache/typegen/graphql.config.jsonwas created.
You can now use npm run lint and npm run lint:fix to check your GraphQL queries, e.g. if they are named.