CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-graphql-codegen--cli

A tool that generates code out of your GraphQL schema and GraphQL operations with extensive plugin ecosystem

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

GraphQL Code Generator

GraphQL Code Generator is a tool that generates code out of your GraphQL schema and GraphQL operations. Whether you are developing a frontend or backend, you can utilize GraphQL Code Generator to generate output from your GraphQL Schema and GraphQL Documents (query/mutation/subscription/fragment).

Package Information

  • Package Name: @graphql-codegen/cli
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install @graphql-codegen/cli

Core Imports

import { executeCodegen, generate, CodegenConfig } from "@graphql-codegen/cli";
import { codegen } from "@graphql-codegen/core";

For CommonJS:

const { executeCodegen, generate } = require("@graphql-codegen/cli");
const { codegen } = require("@graphql-codegen/core");

Basic Usage

CLI Usage

Initialize a new GraphQL Code Generator setup:

# Initialize setup with interactive prompts
npx graphql-code-generator init

# Generate code using config file
npx graphql-codegen

# Generate with watch mode
npx graphql-codegen --watch

# Generate from specific config file
npx graphql-codegen --config ./my-codegen.yml

Programmatic Usage

import { executeCodegen, CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: './src/**/*.graphql',
  generates: {
    './src/generated/graphql.ts': {
      plugins: ['typescript', 'typescript-operations'],
      config: {
        scalars: {
          DateTime: 'Date'
        }
      }
    }
  }
};

// Execute code generation
const result = await executeCodegen({ 
  config,
  cwd: process.cwd(),
  silent: false
});

Architecture

GraphQL Code Generator is built around several key components:

  • CLI Layer: Command-line interface for running code generation with various options and flags
  • Configuration System: Flexible configuration loading from multiple file formats (JSON, YAML, JS, TS)
  • Core Engine: The main codegen engine that processes schemas and documents
  • Plugin System: Extensible plugin architecture for generating different output formats
  • Schema & Document Loading: Supports loading from files, URLs, and various sources
  • Watch Mode: File watching capabilities for development workflows

Capabilities

CLI Commands

Command-line interface for running GraphQL Code Generator with various options.

/**
 * CLI command for initializing GraphQL Code Generator setup
 * Creates configuration file and installs necessary dependencies
 */
declare const init: () => Promise<void>;

/**
 * Main CLI command for running code generation
 * @param argv - Command line arguments including config path, watch mode, profile options
 */
declare const cli: (argv: string[]) => Promise<void>;

Code Generation Execution

Core functionality for executing the code generation process.

/**
 * Executes code generation based on provided configuration
 * @param input - CodegenContext or Config object
 * @returns Promise resolving to file output results
 */
function executeCodegen(input: CodegenContext | Types.Config): Promise<Types.FileOutput[]>;

/**
 * Generate and save files to disk based on configuration
 * @param input - CodegenContext or Config with optional cwd
 * @param saveToFile - Whether to save generated files to disk
 * @returns Promise resolving to file outputs
 */
function generate(
  input: CodegenContext | (Types.Config & { cwd?: string }),
  saveToFile?: boolean
): Promise<Types.FileOutput[]>;

Configuration Management

Configuration loading and management functionality.

/**
 * Load GraphQL Code Generator configuration from various sources
 * @param options - Configuration loading options
 * @returns Promise resolving to loaded configuration
 */
function loadCodegenConfig(options?: LoadCodegenConfigOptions): Promise<{
  config: CodegenConfig;
  filepath: string;
}>;

/**
 * Create a codegen context from CLI flags
 * @param cliFlags - CLI flags for configuration
 * @returns Promise resolving to CodegenContext instance
 */
function createContext(cliFlags?: YamlCliFlags): Promise<CodegenContext>;

/**
 * Ensure input is a proper CodegenContext
 * @param input - Config or CodegenContext
 * @returns CodegenContext instance
 */
function ensureContext(input: CodegenContext | Types.Config): CodegenContext;

Core Code Generation

Low-level code generation functionality from the core package.

/**
 * Core codegen function that processes schema and documents with plugins
 * @param options - Generation options including schema, documents, plugins, and config
 * @returns Promise resolving to generated code string
 */
function codegen(options: Types.GenerateOptions): Promise<string>;

/**
 * Execute a single plugin with provided options
 * @param options - Plugin execution options
 * @returns Promise resolving to plugin output
 */
function executePlugin(options: ExecutePluginOptions): Promise<Types.ComplexPluginOutput>;

Types

/** Main configuration interface for GraphQL Code Generator */
interface CodegenConfig {
  /** GraphQL schema source(s) */
  schema: string | string[] | Types.Schema;
  /** GraphQL documents source(s) */
  documents?: string | string[] | Types.OperationDocument[];
  /** Output configuration mapping file paths to generation settings */
  generates: { [outputPath: string]: Types.ConfiguredOutput };
  /** Global configuration options */
  config?: { [key: string]: any };
  /** Require statements for loading additional modules */
  require?: string[];
  /** Plugin map for custom plugin loading */
  pluginMap?: { [pluginName: string]: Types.CodegenPlugin };
  /** Preset map for custom preset loading */
  presetMap?: { [presetName: string]: Types.OutputPreset };
  /** Watch mode configuration */
  watch?: boolean | string | string[];
  /** Whether to overwrite existing files */
  overwrite?: boolean;
  /** Silent mode flag */
  silent?: boolean;
  /** Lifecycle hooks */
  hooks?: Types.LifecycleHooks;
  /** Debug mode flag */
  debug?: boolean;
  /** Ignore documents validation errors */
  ignoreNoDocuments?: boolean;
  /** Emit legacy CommonJS imports */
  emitLegacyCommonJSImports?: boolean;
}

/** Context object that manages configuration and execution state */
interface CodegenContext {
  /** Get the current configuration */
  getConfig(): Types.Config;
  /** Get the current working directory */
  getCwd(): string;
  /** Get the profiler instance */
  profiler: Types.Profiler;
  /** Update configuration */
  updateConfig(config: Partial<Types.Config>): void;
}

/** CLI flags interface */
interface YamlCliFlags {
  /** Path to configuration file */
  config: string;
  /** Watch mode configuration */
  watch: boolean | string | string[];
  /** Modules to require before execution */
  require: string[];
  /** Overwrite existing files */
  overwrite: boolean;
  /** GraphQL project name */
  project: string;
  /** Silent mode */
  silent: boolean;
  /** Show errors only */
  errorsOnly: boolean;
  /** Enable profiling */
  profile: boolean;
  /** Check mode - validate without generating */
  check?: boolean;
  /** Verbose output */
  verbose?: boolean;
  /** Debug mode */
  debug?: boolean;
  /** Ignore no documents error */
  ignoreNoDocuments?: boolean;
  /** Emit legacy CommonJS imports */
  emitLegacyCommonJSImports?: boolean;
}

/** Configuration loading options */
interface LoadCodegenConfigOptions {
  /** Path to config file or directory containing config file */
  configFilePath?: string;
  /** Name of the config file */
  moduleName?: string;
  /** Additional search places for config file */
  searchPlaces?: string[];
  /** Custom config loaders */
  loaders?: { [extension: string]: CodegenConfigLoader };
}

/** Custom configuration loader function */
type CodegenConfigLoader = (filepath: string, content: string) => Promise<Types.Config> | Types.Config;

/** Plugin execution options */
interface ExecutePluginOptions {
  /** Plugin name or function */
  name: string;
  /** Plugin configuration */
  config: { [key: string]: any };
  /** GraphQL schema */
  schema: Types.Schema;
  /** GraphQL documents */
  documents: Types.DocumentFile[];
  /** Output filename */
  outputFilename: string;
  /** All plugins being executed */
  allPlugins: Types.ConfiguredPlugin[];
  /** Skip documents validation */
  skipDocumentsValidation?: Types.SkipDocumentsValidationOptions;
}

/** File output result */
interface FileOutput {
  /** Output filename */
  filename: string;
  /** Generated content */
  content: string;
  /** Content hash for change detection */
  hash?: string;
}

/** Plugin output interface */
interface ComplexPluginOutput {
  /** Content to prepend to output */
  prepend?: string[];
  /** Main content */
  content: string;
  /** Content to append to output */
  append?: string[];
}

Plugin System Integration

GraphQL Code Generator supports an extensive plugin ecosystem with over 100 plugins available:

Popular Plugin Categories

  • TypeScript: Generate TypeScript types and operations
  • Flow: Generate Flow types
  • React: Generate React hooks and components
  • Angular: Generate Angular services and types
  • Vue: Generate Vue composition API
  • Database: Generate database operations and resolvers
  • Testing: Generate test utilities and mocks

Plugin Usage Example

const config: CodegenConfig = {
  schema: './schema.graphql',
  documents: './src/**/*.graphql',
  generates: {
    './src/generated/': {
      preset: 'client',
      plugins: []
    },
    './src/generated/graphql.ts': {
      plugins: [
        'typescript',
        'typescript-operations',
        'typescript-react-apollo'
      ],
      config: {
        withHooks: true,
        withComponent: false
      }
    }
  }
};

The plugin system allows for complete customization of code generation output, making GraphQL Code Generator adaptable to any project structure or technology stack.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@graphql-codegen/cli@3.3.x
Publish Source
CLI
Badge
tessl/npm-graphql-codegen--cli badge