Apollo Elements Apollo Elements Guides API Blog Toggle darkmode

Getting Started: Codegen

Using the @graphql-codegen/cli package and its plugins, you can automatically generate TypeScript typings from your schema and query documents.

Install Dependencies

npm i -D \
  @graphql-codegen/cli \
  @graphql-codegen/typescript \

Or if you use yarn:

yarn add -D \
  @graphql-codegen/cli \
  @graphql-codegen/typescript \

Configure GraphQL Code Generator

Create a file called .graphqlrc.yml in your project root and paste in these contents:

schema: 'https://api.app.dev/graphql' # replace with url to your graphql server

    config: # season to taste
      constEnums: true            # use `const enum` to define unions
      declarationKind: interface  # use `interface` keyword to define types
      dedupeOperationSuffix: true # prevent `MyQueryQuery`
      documentVariableSuffix: ''  # export `MyQuery` instead of `MyQueryDocument`
      immutableTypes: true        # add `readonly` keyword to frozen objects
      namingConvention: keep      # don't rename types
      operationResultSuffix: Data # add `Data` suffix to result types
      optionalResolveType: true   # make `__resolveType` field optional
      useIndexSignature: true     # required for compatibility with apollo server

      # generate the base schema types for client-side documents
        schema: src/client.schema.graphql
          - typescript-operations
      # generate `.ts` files colocated with each `.graphql` operation
        schema: src/client.schema.graphql
        preset: near-operation-file
          baseTypesPath: schema.ts
          extension: .graphql.ts
          - typescript-operations
          - typed-document-node
          - src/**/*.fragment.graphql
          - src/**/*.mutation.graphql
          - src/**/*.query.graphql
          - src/**/*.subscription.graphql

Now, to automatically generate typings, run

npx graphql-codegen --watch

This has the added benefit of linting your graphql files for errors.

Read more about graphql-codegen on their webpage