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:
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:
Install
npm i -D @graphql-codegen/near-operation-file-preset
Configure the preset
To use this preset, you need to add 2 outputs to your codegen.ts
file:
- The first is the base types, generated by
typescript
plugin. - The second is the one in charge of generating types per operation.
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
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.
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.
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.
npm run generate
For more advanced configuration, please refer to the @graphql-codegen/near-operation-file-preset
documentation.