website/src/pages/docs/config-reference/lifecycle-hooks.mdx
import { Callout } from '@theguild/components'
The codegen allows specifying scripts it can run for you in certain events.
You can specify hooks on the root level or specify hooks on the output level (only some of them).
Each hook has its arguments, and it passes them to your scripts using argv.
Add your scripts to your codegen.ts file, and specify the scripts you wish to run, for example:
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql',
documents: ['src/**/*.tsx'],
generates: {
'./src/gql/': {
preset: 'client'
}
},
hooks: {
afterOneFileWrite: ['prettier --write']
}
}
export default config
Or, for specific output:
import { CodegenConfig } from '@graphql-codegen/cli'
const config: CodegenConfig = {
schema: 'http://localhost:4000/graphql',
documents: ['src/**/*.tsx'],
generates: {
'./src/gql/': {
preset: 'client',
hooks: {
afterOneFileWrite: ['prettier --write']
}
}
}
}
export default config
The following lifecycle hooks are supported on the root level:
afterStartTriggered with no arguments when the codegen starts (after the codegen.ts has been loaded).
onWatchTriggeredTriggered every time a file changes when using watch mode.
Triggered with two arguments: the type of the event (for example, changed) and the file's path.
onErrorTriggered in case of a general error in the codegen. The argument is a string containing the error.
beforeAllFileWriteExecuted after the codegen has created the output and before writing the files to the file system.
Triggered with multiple arguments - paths for all relevant files.
<Callout> Not all the files will be written to the file system, because this is triggered before checking if the file has changed since last execution. </Callout>beforeOneFileWriteTriggered before a file is written to the file system. Executed with the path for the file.
If the content of the file hasn't changed since the last execution - this hook won't be triggered.
afterOneFileWriteTriggered after a file is written to the file system. Executed with the path for the file. If the content of the file hasn't changed since the last execution - this hook won't be triggered.
<Callout>This is a very useful hook, you can use it for integration with Prettier or other linters.</Callout>
afterAllFileWriteExecuted after writing all the files to the file system. Triggered with multiple arguments - paths for all files.
beforeDoneTriggered with no arguments, right before the codegen closes or when watch mode is stopped.
The following hooks are available for a single output file: beforeOneFileWrite and afterOneFileWrite.
Output level hooks are triggered before root level hooks.