6 Feb 2023
The GraphQL Code Generator client-preset
is a great way to generate a TypedDocumentNode
for all GraphQL operations of your application.
You can also use the client-preset
to automatically persist documents to JSON for use with your GraphQL server to only allow the operations used by your application.
This prevents unwanted operations from being executed by your server.
To begin you will want to install the GraphQL Code Generator dependencies:
npm install --save-dev typescript @graphql-codegen/cli @graphql-codegen/client-preset
Finally don't forget to install graphql
itself as a dependency:
npm install graphql
Inside the root of your project create the file codegen.ts
:
touch codegen.ts
Then add the following configuration but make sure to update the path to your schema
(which can be a URL), the documents
glob and pass persistedDocuments: true
to the generator:
import { CodegenConfig } from "@graphql-codegen/cli";
const config: CodegenConfig = {
schema: "YOUR_GRAPHQL_ENDPOINT",
documents: ["app/**/*.{ts,tsx}"],
ignoreNoDocuments: true,
generates: {
"./gql/": {
preset: "client",
plugins: [],
presetConfig: {
persistedDocuments: true,
},
},
},
};
export default config;
You can learn more about all of the configuration above and what it means in Episode 67.