I created a repository where I show how to automatically generate Typescript types from a GraphQL schema using Nx. This works both while running the serve
and the build
commands. The repository consists of a Node.js Apollo Server application which can be run using npm run serve
.
In order to get the generation of types working, I used @graphql-codegen/cli
. This honestly is an amazing package. It generates the Typescript types in a neat way, and it can even generate types for your resolvers. This way it is pretty easy to make your entire application type safe.
The portion I added myself can be found in the webpack.config.js
override. I added a custom Webpack plugin which runs every time a watch or a build is triggered. This plugins checks if the changed file is typeDefs.ts
, and if so, it runs the npm run generate-gql-types
command. A pretty simple trick, but it can save a lot of frustration over time!
Cheers!
View on GitHub