Generating TypeScript types for Gatsby.js GraphQL Schema

When I started working with Gatsby and TypeScript, I started defining interfaces myself based on the queries I was writing for the pages. This started to get tedious. If you are using the TypeScript starter, as I was, there is a comment in the index page:

// Please note that you can use https://github.com/dotansimha/graphql-code-generator
// to generate all types from graphQL schema

Once installed, I was able to generate types for my site easily.

gql-gen --url http://localhost:8001/___graphql --template typescript --out ./src/graphql.d.ts

You might notice that this command assumes the GraphQL server is running. The other option specified in the graphql-code-generator docs is to specify a GraphQL schema.json file. I looked into generating that, but it also requires the GraphQL server to be running as it runs an introspection query to genrate the file.

So downside to generating these types is that there isn't a good way to automate the above script. It would be cool to hook into the Gatsby.js build process but that doesn't seem to be an option right now. Since the structure of the content doesn't change very often I think it's a reasonable trade-off.