Code generation means the automatic generation of TypeScript types based on your GraphQL schema and your GraphQL operations. This is a very powerful feature that allows you to write your code in a type-safe manner, without you needing to manually write any types for your API calls.
To do this, we will use Graphql Code Generator.
Use npx vendure add and select "Set up GraphQL code generation" to quickly set up code generation.
You can then run npx vendure schema to generate a schema.graphql file in your root
directory.
This guide is for adding codegen to your Vendure plugins. For a guide on adding codegen to your storefront, see the Storefront Codegen guide.
It is recommended to use the vendure add CLI command as detailed above to set up codegen.
If you prefer to set it up manually, follow the steps below.
First, install the required dependencies:
Add a codegen.ts file to your project root with the following contents:
This assumes that we have an "organization" plugin which adds support for grouping customers into organizations, e.g. for B2B use-cases.
You can now add a script to your package.json to run codegen:
Ensure your server is running, then run the codegen script:
This will generate a file at src/plugins/organization/gql/generated.ts which contains all the GraphQL types corresponding to your schema.
You would then use these types in your resolvers and service methods, for example:
In your service methods you can directly use any input types defined in your schema:
You do not need to set up codegen for your Dashboard extensions. The Dashboard has built-in GraphQL type safety for the operations you define in your extension code, and requires no additional setup.
You can also set up file watching as described in the Graphql Code Generator watch mode docs.
Architecture reviews, custom plugin work, migrations, ongoing support. Get a hand from the team that builds Vendure.
Talk to the team