website/src/pages/docs/advanced/generated-files-colocation.mdx
import { Callout } from '@theguild/components'
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{:ts} flag.
Most GraphQL Code Generator configuration examples (in guides or plugins documentation) generate types in a single common file, as follows:
import { CodegenConfig } from '@graphql-codegen/cli';
// Configuration for a React URQL setup
const config: CodegenConfig = {
schema: 'http://my-graphql-api.com/graphql',
documents: './src/**/*.tsx',
generates: {
'graphql/generated.ts': {
plugins: ['typescript', 'typescript-operations', 'typescript-urql'],
config: { withHooks: true },
},
},
};
export default config;
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:
npm i -D @graphql-codegen/near-operation-file-preset
To use this preset, you need to add 2 outputs to your codegen.ts file:
typescript plugin.import { CodegenConfig } from '@graphql-codegen/cli';
const config: CodegenConfig = {
schema: 'http://my-graphql-api.com/graphql',
documents: 'src/**/!(*.generated).{ts,tsx}',
generates: {
'src/types.ts': {
plugins: ['typescript'],
},
'src/': {
preset: 'near-operation-file',
presetConfig: { extension: '.generated.tsx', baseTypesPath: 'types.ts' },
plugins: ['typescript-operations', 'typescript-urql'],
config: { withHooks: true },
},
},
};
export default config;
schema needs to be your target GraphQL API URL ("/graphql" included).
documents is a glob expression to your .graphql, .ts or .tsx files.
Assuming that, as recommended, your package.json has the following script:
{
"scripts": {
"generate": "graphql-codegen"
}
}
Running the following generates the colocated .generated.tsx file.
npm run generate
For more advanced configuration, please refer to the @graphql-codegen/near-operation-file-preset documentation.