GraphQL Code Generator also provides a complete programmatic API. The programmatic API can be used if you need to customize the execution flow or write a tool that uses the codegen.
GraphQL Code Generator also provides a complete programmatic API.
The programmatic API can be used if you need to customize the execution flow or write a tool that
uses the codegen.
Basic Programmatic Usage
In order to use the programmatic API, start by importing codegen from @graphql-codegen/core:
import fs from 'node:fs'import path from 'node:path'import { buildSchema, GraphQLSchema, parse, printSchema } from 'graphql'import * as typescriptPlugin from '@graphql-codegen/typescript'const schema: GraphQLSchema = buildSchema(`type A { name: String }`)const outputFile = 'relative/pathTo/filename.ts'const config = { documents: [], config: {}, // used by a plugin internally, although the 'typescript' plugin currently // returns the string output, rather than writing to a file filename: outputFile, schema: parse(printSchema(schema)), plugins: [ // Each plugin should be an object { typescript: {} // Here you can pass configuration to the plugin } ], pluginMap: { typescript: typescriptPlugin }}
Notice that a plugin name key in pluginMap and plugins must match to identify a plugin and its
configuration.
If you wish to have the benefits that cli package has (like loading schema and document files,
parsing endpoints and more), you can use require() (or import) for @graphql-codegen/cli
directly with Node.JS: