ts-patch

May 1, 2026 · View on GitHub

npm version NPM Downloads Build Status

ts-patch

Patch typescript to allow custom transformers (plugins) during build.

Plugins are specified in tsconfig.json, or provided programmatically in CompilerOptions.

Important

ts-patch v4 supports TypeScript 6 and later only. For TypeScript 5 projects, use ts-patch v3.

Migrating from ttypescript is easy! See: Method 1: Live Compiler

Features

  • Patch typescript via on-the-fly, in-memory compiler routes or persistent patches for supported files
  • Can patch supported compiler libraries (see ts-patch /?)
  • Hook build process by transforming the Program (see: Transforming Program)
  • Add, remove, or modify diagnostics (see: Altering Diagnostics)
  • Fully compatible with legacy ttypescript projects
  • (new) Experimental support for ES Module based transformers

Table of Contents

Installation

  1. Install package
<yarn|npm|pnpm> add -D ts-patch

Usage

Method 1: Live Compiler

The live compiler patches on-the-fly, each time it is run.

Via commandline: Simply use tspc (instead of tsc)

With tools such as ts-node, webpack, ts-jest, etc: specify the compiler as ts-patch/compiler

Additional live routes are available for tools that need a specific TypeScript entry:

RouteLibrary identity supplied to transformers
ts-patch/compilertypescript
ts-patch/compiler/typescripttypescript
ts-patch/compiler/tsctsc
ts-patch/compiler/tsservertsserver
ts-patch/compiler/tsserverlibrarytsserverlibrary

Method 2: Persistent Patch

Persistent patching modifies supported TypeScript files inside node_modules. It is still available for TypeScript 6, but the patchable surface is narrower than it was in earlier TypeScript versions.

TypeScript 6 ships thin entry shims for several library files. Some service entries delegate to shared implementation files; for example, tsserverlibrary.js delegates to typescript.js. Rewriting those service files in place would not preserve enough entry context to distinguish direct compiler API use from tsc, tsserver, or tsserverlibrary use. For those entries, use the live compiler routes instead.

install and uninstall remain available, but they now affect only typescript.js and tsc.js:

ts-patch install
ts-patch uninstall

The lower-level patch and unpatch commands are also limited to those two targets:

ts-patch patch typescript tsc
ts-patch unpatch typescript tsc

tsserver.js and tsserverlibrary.js are not persistent patch targets on TypeScript 6. Use the live routes above so transformers still receive the correct library identity for those service entries.

Configuration

tsconfig.json: Add transformers to compilerOptions in plugins array.

Examples

{
    "compilerOptions": {
        "plugins": [
            // Source Transformers
            { "transform": "transformer-module" },
            { "transform": "transformer2", "extraOption": 123 },
            { "transform": "trans-with-mapping", "resolvePathAliases": true },
            { "transform": "esm-transformer.mjs" },

            // Program Transformer
            { "transform": "transformer-module5", "transformProgram": true }
        ]
    }
}

Plugin Options

OptionTypeDescription
transformstringModule name or path to transformer (*.ts or *.js)
afterbooleanApply transformer after stock TS transformers
afterDeclarationsbooleanApply transformer to declaration (*.d.ts) files
transformProgrambooleanTransform Program during ts.createProgram() (see: Program Transformers)
resolvePathAliasesbooleanResolve path aliases in transformer (requires tsconfig-paths)
typestringSee: Source Transformer Entry Point (default: 'program')
importstringName of exported transformer function (defaults to default export)
tsConfigstringtsconfig.json file for transformer (allows specifying compileOptions, path mapping support, etc)
...Provide your own custom options, which will be passed to the transformer

Note: Required options are bold

As of v4, isEsm has been removed. Transformer module format is inferred from the file extension and package metadata.

Writing Transformers

For an overview of the typescript compiler (such as what a SourceFile and Program is) see: Typescript Compiler Notes.

Source Transformers

Source Transformers will transform the AST of SourceFiles during compilation, allowing you to alter the output of the JS or declarations files.

Source Transformer Entry Point

(program: ts.Program, config: PluginConfig, extras: TransformerExtras) => ts.TransformerFactory

PluginConfig: Type Declaration
TransformerExtras: Type Declaration
ts.TransformerFactory: (context: ts.TransformationContext) => (sourceFile: ts.SourceFile) => ts.SourceFile

Note: Additional legacy signatures are supported, but it is not recommended to develop a new transformer using them.

Source Transformer Example

Transformers can be written in JS or TS.

import type * as ts from 'typescript';
import type { TransformerExtras, PluginConfig } from 'ts-patch';

/** Changes string literal 'before' to 'after' */
export default function (program: ts.Program, pluginConfig: PluginConfig, { ts: tsInstance }: TransformerExtras) {
  return (ctx: ts.TransformationContext) => {
    const { factory } = ctx;
    
    return (sourceFile: ts.SourceFile) => {
      function visit(node: ts.Node): ts.Node {
        if (tsInstance.isStringLiteral(node) && node.text === 'before') {
          return factory.createStringLiteral('after');
        }
        return tsInstance.visitEachChild(node, visit, ctx);
      }
      return tsInstance.visitNode(sourceFile, visit);
    };
  };
}

Live Examples:

{ transform: "typescript-transform-paths" }

{ transform: "typescript-is/lib/transform-inline/transformer" }

{ transform: "typia/lib/transform" } (💻playground)

{ transform: "@nestia/core/lib/transform" }

Altering Diagnostics

Diagnostics can be altered in a Source Transformer.

To alter diagnostics you can use the following, provided from the TransformerExtras parameter:

propertydescription
diagnosticsReference to Diagnostic array
addDiagnostic()Safely add Diagnostic to diagnostics array
removeDiagnostic()Safely remove Diagnostic from diagnostics array

Note

This alters diagnostics during emit only. If you want to alter diagnostics in your IDE as well, you'll need to create a LanguageService plugin to accompany your source transformer

Program Transformers

Sometimes you want to do more than just transform source code. For example you may want to:

  • TypeCheck code after it's been transformed
  • Generate code and add it to the program
  • Add or remove emit files during transformation

For this, we've introduced what we call a Program Transformer. The transform action takes place during ts.createProgram, and allows re-creating the Program instance that typescript uses.

Program Transformer Entry Point

(program: ts.Program, host: ts.CompilerHost | undefined, options: PluginConfig, extras: ProgramTransformerExtras) => ts.Program

ProgramTransformerExtras >>> Type Declaration

Configuring Program Transformers

To configure a Program Transformer, supply "transformProgram": true in the config transformer entry.

Note: The before, after, and afterDeclarations options do not apply to a Program Transformer and will be ignored

See Config Example

Program Transformer Example

/** 
 * Add a file to Program
 */
import * as path from 'path';
import type * as ts from 'typescript';
import type { ProgramTransformerExtras, PluginConfig } from 'ts-patch';

export const newFile = path.resolve(__dirname, 'added-file.ts');

export default function (
  program: ts.Program, 
  host: ts.CompilerHost | undefined, 
  options: PluginConfig, 
  { ts: tsInstance }: ProgramTransformerExtras
) {
  return tsInstance.createProgram(
    /* rootNames */ program.getRootFileNames().concat([ newFile ]),
    program.getCompilerOptions(),
    host,
    /* oldProgram */ program
  );
}

Note: For a more complete example, see Transforming Program with additional AST transformations

Live Examples:

{ transform: "@typescript-virtual-barrel/compiler-plugin", transformProgram: true }

{ transform: "ts-overrides-plugin", transformProgram: true }

Plugin Package Configuration

The plugin package configuration allows you to specify custom options for your TypeScript plugin. This configuration is defined in the package.json of your plugin under the tsp property.

An example use case is enabling parseAllJsDoc if you require full JSDoc parsing in tsc for your transformer in TS v5.3+. (see: 5.3 JSDoc parsing changes)

For all available options, see the PluginPackageConfig type in plugin-types.ts

Example

{
  "name": "your-plugin-name",
  "version": "1.0.0",
  "tsp": {
    "tscOptions": {
      "parseAllJsDoc": true
    }
  }
}

Resources

ToolTypeDescription
TS AST ViewerWeb AppAllows you to see the Node structure and other TS properties of your source code.
ts-expose-internalsNPM PackageExposes internal types and methods of the TS compiler API

Discussion

Advanced Options

(env) TSP_SKIP_CACHE

Skips patch cache when patching via cli or live compiler.

(env) TSP_COMPILER_TS_PATH

Specify typescript library path to use for ts-patch/compiler (defaults to require.resolve('typescript'))

(env) TSP_CACHE_DIR

Override patch cache directory

(cli) ts-patch clear-cache

Cleans patch cache & lockfiles

Compatibility Direction

TypeScript 6 changed the compiler distribution shape by introducing thin CommonJS shims around several implementation files. ts-patch uses live routing where entry identity matters because a live route can preserve whether a tool requested typescript, tsc, tsserver, or tsserverlibrary without permanently rewriting service-entry shims.

For TypeScript 6, persistent patching is intentionally narrow: only typescript.js and tsc.js are patchable targets. Service entries should be loaded through ts-patch/compiler/tsserver or ts-patch/compiler/tsserverlibrary.

The TypeScript team has also announced a future Go-based compiler line. ts-patch will evaluate that implementation as a separate compatibility track, including whether the JavaScript compiler API and transformer hooks remain available or whether a redesigned integration is required.

Maintainers


Ron S.

Help Wanted

If you're interested in helping and are knowledgeable with the TS compiler codebase, feel free to reach out!

License

This project is licensed under the MIT License, as described in LICENSE.md