{"id":12184,"library":"ts-patch","title":"ts-patch","description":"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.","status":"active","version":"3.3.0","language":"javascript","source_language":"en","source_url":"ssh://git@github.com/nonara/ts-patch","tags":["javascript","typescript","transform","transformer","plugin","config","ast"],"install":[{"cmd":"npm install ts-patch","lang":"bash","label":"npm"},{"cmd":"yarn add ts-patch","lang":"bash","label":"yarn"},{"cmd":"pnpm add ts-patch","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"ts-patch directly patches and interacts with the TypeScript compiler API; it functions as a drop-in replacement or wrapper for `typescript`.","package":"typescript","optional":false}],"imports":[{"note":"Programmatic patching/unpatching of TypeScript. While CLI `ts-patch install` is more common, these functions are available for advanced use cases.","wrong":"const patch = require('ts-patch').patch;","symbol":"patch","correct":"import { patch } from 'ts-patch';"},{"note":"Used to revert changes made by `patch`. Typically, the CLI `ts-patch uninstall` is used.","wrong":"const unpatch = require('ts-patch').unpatch;","symbol":"unpatch","correct":"import { unpatch } from 'ts-patch';"},{"note":"When integrating with build tools (e.g., ts-node, webpack via ts-loader, Jest via ts-jest), `ts-patch/compiler` is provided as the compiler module. It exports a function compatible with `ts.createProgram`.","wrong":"import { createProgram } from 'ts-patch/compiler';","symbol":"createProgram","correct":"import createProgram from 'ts-patch/compiler';"}],"quickstart":{"code":"import * as ts from 'typescript';\n\n// 1. Define a simple TypeScript AST transformer\n// This transformer appends a comment to every variable statement.\nconst myTransformer: ts.TransformerFactory<ts.SourceFile> = (context) => {\n    return (rootNode) => {\n        function visit(node: ts.Node): ts.Node {\n            if (ts.isVariableStatement(node)) {\n                // Add a synthetic leading comment to the variable statement\n                const commentText = '/** Transformed by ts-patch **/ ';\n                return ts.addSyntheticLeadingComment(\n                    node,\n                    ts.SyntaxKind.MultiLineCommentTrivia,\n                    commentText,\n                    true // New line after comment\n                );\n            }\n            return ts.visitEachChild(node, visit, context);\n        }\n        return ts.visitNode(rootNode, visit);\n    };\n};\n\nexport default myTransformer;\n\n// tsconfig.json\n// {\n//   \"compilerOptions\": {\n//     \"target\": \"es2018\",\n//     \"module\": \"commonjs\",\n//     \"outDir\": \"./dist\",\n//     \"strict\": true,\n//     \"plugins\": [\n//       { \"transform\": \"./my-transformer.ts\" }\n//     ]\n//   }\n// }\n\n// src/index.ts\n// const appName = \"My Awesome App\";\n// console.log(`Welcome to ${appName}`);\n\n// To run:\n// 1. npm install -D typescript ts-patch\n// 2. Create my-transformer.ts, tsconfig.json, and src/index.ts as above.\n// 3. From your terminal, run: npx ts-patch install\n// 4. Then compile: npx tspc\n// 5. Check 'dist/index.js' for the added comment.","lang":"typescript","description":"Demonstrates defining a custom AST transformer, configuring it in `tsconfig.json`, installing `ts-patch`, and compiling with `tspc` to see the transformation effect."},"warnings":[{"fix":"Always keep `ts-patch` updated to its latest version, especially after upgrading your `typescript` dependency. Check the changelog for specific TypeScript version support.","message":"ts-patch requires frequent updates to maintain compatibility with new TypeScript versions. Using an older `ts-patch` version with a newer `typescript` compiler can lead to build failures or unexpected behavior. For example, v3.2.0 added support for TS 5.5, and v3.3.0 for TS 5.7+.","severity":"breaking","affected_versions":"<3.3.0"},{"fix":"To ensure persistence, add `\"prepare\": \"ts-patch install -s\"` to your `package.json` scripts. This hook runs automatically after `npm install` or `yarn install` to re-apply the patch.","message":"The 'persistent patch' method (`ts-patch install`) modifies your `node_modules/typescript` installation. If `node_modules` is cleared or reinstalled (e.g., in CI/CD environments or by package managers), the patch will be lost, leading to build errors.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"Update `tsconfig.json` plugin configurations to use `\"transformProgram\": true` instead of `\"beforeEmit\": true` for program transformers.","message":"The `beforeEmit` option for Program Transformers has been renamed to `transformProgram` to better reflect its behavior. While `beforeEmit` still functions as an alias, using the new `transformProgram` is recommended for clarity and future compatibility.","severity":"deprecated","affected_versions":"<3.0.0"},{"fix":"For `ts-node`, use `--compiler ts-patch/compiler`. For `ts-jest`, set `globals['ts-jest'].compiler = 'ts-patch/compiler'` in your Jest config. For `ts-loader`, configure `compiler: 'ts-patch/compiler'` in its options.","message":"When using `ts-patch` in build tools like `ts-node`, `webpack` (via `ts-loader`), or `Jest` (via `ts-jest`), you must explicitly configure them to use `ts-patch/compiler` as the TypeScript compiler. Failing to do so will result in custom transformers not being applied.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure your build tool's configuration points to `ts-patch/compiler` as the compiler path. For example, `ts-node --compiler ts-patch/compiler` or in `jest.config.js`: `globals['ts-jest'].compiler = 'ts-patch/compiler'`.","cause":"The build tool (e.g., ts-node, webpack, Jest) is not correctly configured to use `ts-patch/compiler` as its TypeScript compiler.","error":"Error: Cannot find module 'ts-patch/compiler'"},{"fix":"Update `ts-patch` to the latest version. If using persistent patching, ensure `npm run prepare` (or `ts-patch install`) has been run successfully after `npm install`.","cause":"Your `ts-patch` version is incompatible with your installed `typescript` version, or the persistent patch was not applied.","error":"TypeError: Cannot read properties of undefined (reading 'createSourceFile') or similar errors related to TypeScript API"},{"fix":"Verify the transformer module's name in `tsconfig.json` is correct and it is listed in `package.json` dependencies. If it's a local file, ensure the path is relative to `tsconfig.json` and includes the `.ts` or `.js` extension if not directly resolvable.","cause":"The transformer module specified in `tsconfig.json`'s `plugins` array is either not installed, the path is incorrect, or it cannot be resolved by Node.js module resolution.","error":"Plugin 'your-transformer-module' not found. Make sure it's installed or the path is correct."},{"fix":"Try running `ts-patch uninstall` if you believe it's partially unpatched. If problems persist, a fresh `rm -rf node_modules && npm install` followed by `ts-patch install` might be necessary. This specific issue was also addressed in v3.0.1 with a more explicit error.","cause":"This error can occur if `ts-patch` attempts to restore a backup of `typescript.js` but the backup file is missing, likely due to manual deletion or an interrupted `ts-patch uninstall`.","error":"ENOENT: no such file or directory, stat '/path/to/node_modules/typescript/lib/typescript.js.bak'"}],"ecosystem":"npm"}