Implement GraphQL code generation
GraphQL code generation automatically creates strongly typed code based on your schema and operations. It generates type-safe code artifacts using the graphql-codegen package, ensuring consistency between the front-end implementation and the underlying GraphQL API.
You can follow this topic to manually implement GraphQL code generation in your app using the graphql-codegen package.
To implement GraphQL code generation:
-
Add the following dev dependencies to your app's
package.jsonfile, then install them with thenpm installcommand. -
Enable fetching of GraphQL introspection data by adding the following example script to the
/scripts/fetch-graphql-introspection-data.tsfile:This file fetches the GraphQL introspection data exposed by SItecore instance's GraphQL API and stores it in
./sitecore/GraphQLIntrospectionResult.json. This file is used to generate the TypeScript types. -
To import
scConfigproperly in the above script, add the following extension in thetsconfig.scripts.jsonfile: -
Add the following script in the
scriptssection of your application's package.json file: -
Configure
graphql-codegenby creating agraphql-codegen.ymlat the root of your app containing the following: -
Run the following command to generate the
src/temp/graphql-types.tsfile containing the necessary types.