ts-patch

3.3.0 · active · verified Sun Apr 19

ts-patch is a utility that augments the TypeScript compiler to enable the use of custom Abstract Syntax Tree (AST) transformers and plugins during the build process. It allows developers to specify these transformers directly within `tsconfig.json` or to provide them programmatically via `CompilerOptions`. The current stable version is 3.3.0, with frequent releases to ensure compatibility with the latest TypeScript versions, such as adding support for TypeScript 5.7+ in the most recent update. Key differentiators include its dual approach to patching: an on-the-fly 'live compiler' (accessed via `tspc` or by specifying `ts-patch/compiler` in build tools) and a 'persistent patch' method that modifies the `node_modules` installation. It offers full compatibility with legacy `ttypescript` projects and supports both source-level and program-level transformations, with experimental support for ES Module-based transformers.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining a custom AST transformer, configuring it in `tsconfig.json`, installing `ts-patch`, and compiling with `tspc` to see the transformation effect.

import * as ts from 'typescript';

// 1. Define a simple TypeScript AST transformer
// This transformer appends a comment to every variable statement.
const myTransformer: ts.TransformerFactory<ts.SourceFile> = (context) => {
    return (rootNode) => {
        function visit(node: ts.Node): ts.Node {
            if (ts.isVariableStatement(node)) {
                // Add a synthetic leading comment to the variable statement
                const commentText = '/** Transformed by ts-patch **/ ';
                return ts.addSyntheticLeadingComment(
                    node,
                    ts.SyntaxKind.MultiLineCommentTrivia,
                    commentText,
                    true // New line after comment
                );
            }
            return ts.visitEachChild(node, visit, context);
        }
        return ts.visitNode(rootNode, visit);
    };
};

export default myTransformer;

// tsconfig.json
// {
//   "compilerOptions": {
//     "target": "es2018",
//     "module": "commonjs",
//     "outDir": "./dist",
//     "strict": true,
//     "plugins": [
//       { "transform": "./my-transformer.ts" }
//     ]
//   }
// }

// src/index.ts
// const appName = "My Awesome App";
// console.log(`Welcome to ${appName}`);

// To run:
// 1. npm install -D typescript ts-patch
// 2. Create my-transformer.ts, tsconfig.json, and src/index.ts as above.
// 3. From your terminal, run: npx ts-patch install
// 4. Then compile: npx tspc
// 5. Check 'dist/index.js' for the added comment.

view raw JSON →