The Guild LogoThe Guild Monogram

GraphQL Code Generator

Generate anything from GraphQL schema / operations!

Contact Us

Generated files colocation#

Note for back-end use-cases

This page covers the @graphql-codegen/near-operation-file-preset preset, which only applies to front-end projects.

For similar results on a back-end project, please refer to @graphql-codegen/graphql-modules-preset with the useGraphQLModules: false flag.


Most GraphQL Code Generator configuration examples (in guides or plugins documentation) generate types in a single common file, as follows:

# Configuration for a React URQL setup schema: documents: './src/**/*.tsx' generates: graphql/generated.ts: plugins: - typescript - typescript-operations - typescript-urql config: withHooks: true

All code is generated in one single graphql/generated.ts file.

However, you might prefer to have those types generated in files near the original GraphQL operations, as follows:

src/ components/ posts/ posts.generated.tsx Posts.tsx #...

posts.generated.tsx contains the generated code for the GraphQL query used in Posts.tsx.


Just a few configuration steps are required to get this structure of colocated generated files:

1. Install the @graphql-codegen/near-operation-file-preset preset

yarn add @graphql-codegen/near-operation-file-preset

2. Configure the preset

To use this preset, you need to add 2 outputs to your codegen.yml file:

  • The first is the base types, generated by typescript plugin.
  • The second is the one in charge of generating types per operation.

schema: # we are looking for operations in .tsx files, # but not the generated ones. documents: 'src/**/!(*.generated).{ts,tsx}' generates: src/types.ts: - typescript src/: preset: near-operation-file presetConfig: extension: .generated.tsx baseTypesPath: types.ts plugins: - typescript-operations - typescript-urql config: withHooks: true

schema and documents values

schema needs to be your target GraphQL API URL ("/graphql" included).

documents is a glob expression to your .graphql, .ts or .tsx files.

Note: If you're loading your documents from files with the same extension as the generated files, make sure the glob you use excludes the generated files. For example, if your original glob was src/**/*.{ts,tsx}, use src/**/!(*.generated).{ts,tsx} instead.

3. Run the codegen and update your code

Assuming that, as recommended, your package.json has the following script:

{ "scripts": { "generate": "graphql-codegen" } }

Running the following generates the colocated .generated.tsx file.

yarn generate



For more advanced configuration, please refer to the @graphql-codegen/near-operation-file-preset documentation.