Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
ts-patch is a tool that allows you to patch the TypeScript compiler (tsc) to enable custom transformers and other advanced features. It is particularly useful for developers who need to extend the capabilities of TypeScript beyond what is natively supported.
Custom Transformers
This feature allows you to apply custom transformers to the TypeScript compiler. By patching the compiler, you can specify custom transformers in your tsconfig.json file, enabling advanced code transformations during the compilation process.
const { patch, unpatch } = require('ts-patch');
// Apply the patch
patch();
// Now you can use custom transformers in your tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"plugins": [
{ "transform": "./path/to/your/transformer" }
]
}
}
// Unpatch when done
unpatch();
Advanced Compiler Options
This feature allows you to enable advanced compiler options that are not natively supported by TypeScript. By patching the compiler, you can use options like experimental decorators and emit decorator metadata.
const { patch, unpatch } = require('ts-patch');
// Apply the patch
patch();
// Now you can use advanced compiler options in your tsconfig.json
// tsconfig.json
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
// Unpatch when done
unpatch();
Integration with Build Tools
This feature allows you to integrate ts-patch with various build tools like Webpack. By patching the TypeScript compiler, you can use custom transformers and advanced compiler options in your build process.
const { patch, unpatch } = require('ts-patch');
// Apply the patch
patch();
// Now you can integrate ts-patch with build tools like Webpack
// webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.tsx', '.ts', '.js']
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};
// Unpatch when done
unpatch();
ttypescript is a fork of the TypeScript compiler that allows you to use custom transformers directly in your tsconfig.json. It is similar to ts-patch in that it enables advanced TypeScript features, but it requires you to use a different compiler binary.
babel-plugin-transform-typescript-metadata is a Babel plugin that adds support for TypeScript metadata reflection. While it doesn't patch the TypeScript compiler, it provides similar functionality by enabling advanced TypeScript features through Babel.
typescript-transform-paths is a TypeScript transformer that rewrites module paths based on the paths specified in tsconfig.json. It is similar to ts-patch in that it allows for custom transformations, but it focuses specifically on module path rewriting.
Directly patch typescript installation to allow custom transformers (plugins).
tsconfig.json
, or provided programmatically in CompilerOptions
.ts-patch /?
)Program
instance during creation. (see: Transforming Program)<yarn|npm|pnpm> add -D ts-patch
ts-patch install
# For advanced options, see: ts-patch /?
prepare
script (keeps patch persisted after npm installations)package.json
{
/* ... */
"scripts": {
"prepare": "ts-patch install -s"
}
}
With a couple years of hindsight, it's time for a much needed redesign to make a more complete plugin ecosystem that is more multi-package manager friendly. The development of v2 is underway. To follow that progress, see this discussion.
In the mean time, v1 will still be maintained and patched for any issues, and its end of life will be no earlier than 2023.
Add transformers to compilerOptions
in plugins
array.
Examples
{
"compilerOptions": {
"plugins": [
// Source Transformer -> 'type' defaults to 'program'
{ "transform": "transformer-module", "someOption1": 123, "someOption2": 321 },
// Source Transformer -> program signature
{ "transform": "./transformers/my-transformer.ts", "type": "program" },
// Source Transformer -> program signature, applies after TS transformers
{ "transform": "transformer-module1", "type": "config", "after": true },
// Source Transformer -> checker signature, applies to TS declarations
{ "transform": "transformer-module2", "type": "checker", "afterDeclarations": true },
// Source Transformer -> raw signature
{ "transform": "transformer-module3", "type": "raw" },
// Source Transformer -> compilerOptions signature
{ "transform": "transformer-module4", "type": "compilerOptions" },
// Program Transformer -> Only has one signature - notice no type specified, because it does not apply
{ "transform": "transformer-module5", "transformProgram": true }
]
}
}
Option | Type | Description |
---|---|---|
transform | string | Module name or path to transformer (*.ts or *.js) |
type | string | Source Transformer entry point signature (see: Source Transformer Signatures) |
import | string | Name of exported transformer function (defaults to default export) |
tsConfig | string | tsconfig.json file for transformer (allows specifying compileOptions, path mapping support, etc) |
after | boolean | Apply transformer after stock TS transformers. |
afterDeclarations | boolean | Apply transformer to declaration (*.d.ts) files (TypeScript 2.9+). |
transformProgram | boolean | Transform Program during ts.createProgram() (see: Transforming Program) |
... | Provide your own custom options, which will be passed to the transformer |
Note: Required options are bold
The following are the possible values for the type
option and their corresponding entry point signatures.
Note: These apply to Source Transformers only.
Signature with ts.Program
instance:
(program: ts.Program, config: PluginConfig, extras: TransformerExtras) => ts.TransformerFactory
ts.TransformerFactory >>> (context: ts.TransformationContext) => (sourceFile: ts.SourceFile) => ts.SourceFile
TransformerExtras >>> See Type Declaration
Note: This is not the configuration for a Program Transformer.
Signature with transformer's config:
(config: PluginConfig) => ts.TransformerFactory
Signature with ts.TypeChecker
:
(checker: ts.TypeChecker, config: PluginConfig) => ts.TransformerFactory
Signature without ts-patch
wrapper:
/* ts.TransformerFactory */
(context: ts.TransformationContext) => (sourceFile: ts.SourceFile) => ts.SourceFile
(compilerOpts: ts.CompilerOptions, config: PluginConfig) => ts.TransformerFactory
Transformers can be written in JS or TS.
// transformer1-module
import * as ts from 'typescript';
export default function(program: ts.Program, pluginOptions: any) {
return (ctx: ts.TransformationContext) => {
return (sourceFile: ts.SourceFile) => {
function visitor(node: ts.Node): ts.Node {
// if (ts.isCallExpression(node)) {
// return ts.createLiteral('call');
// }
return ts.visitEachChild(node, visitor, ctx);
}
return ts.visitEachChild(sourceFile, visitor, ctx);
};
};
}
{ transform: "typescript-is/lib/transform-inline/transformer" }
{ transform: "ts-transform-img/dist/transform", type: "config" }
{ transform: "ts-transform-css-modules/dist/transform", type: "config" }
{ transform: "ts-transform-react-intl/dist/transform", import: "transform", type: "config" }
{ transform: "ts-nameof", type: "raw" }
{ transform: "typescript-transform-jsx" }
{ transform: "typescript-transform-paths" }
{ transform: "ts-transformer-minify-privates" }
There are some cases where a transformer isn't enough. Several examples are if you want to:
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.
To configure a Program Transformer, supply "transformProgram": true
in the config transformer entry.
Note: The type
, before
, and after
options do not apply to a Program Transformer and will be ignored
There is only one possible signature for a Program Transformer entry point.
(program: ts.Program, host: ts.CompilerHost | undefined, options: PluginConfig, extras: ProgramTransformerExtras) => ts.Program
ProgramTransformerExtras >>> See Type Declaration
/**
* Add a file to Program
*/
import * as ts from 'typescript';
import * as path from 'path';
import { 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
Diagnostics can be altered in a Source Transformer.
To alter diagnostics, use the program type signature, and use the following properties from the
TransformerExtras
parameter
property | description |
---|---|
diagnostics | Reference to Diagnostic[] created during ts.emitFilesAndReportErrors() (works with tsc also) |
addDiagnostic() | Directly add Diagnostic to diagnostics array |
removeDiagnostic() | Directly remove Diagnostic from diagnostics array (uses splice, for safe removal) |
ts.emitFilesAndReportErrors()
is used, any diagnostics added via addDiagnostic()
will still be merged into the result of program.emit() -> diagnostics
Tool | Type | Description |
---|---|---|
TS AST Viewer | Website | Allows you to see the Node structure of any TS/JS source, including Flags, Type , and Symbol . This is the go-to tool for all things TypeScript AST. |
ts-query | NPM Package | Perform fast CSS-like queries on AST to find specific nodes (by attribute, kind, name, etc) |
ts-query Playground | Website | Test ts-query in realtime |
ts-expose-internals | NPM Package | Exposes internal types and methods of the TS compiler API |
Author | Module |
---|---|
Ron S. | ts-patch |
cevek | ttypescript |
#typescript-compiler-api
tag#compiler
room on the TypeScript Discord Server.This project is licensed under the MIT License
FAQs
Patch typescript to support custom transformers in tsconfig.json
The npm package ts-patch receives a total of 94,413 weekly downloads. As such, ts-patch popularity was classified as popular.
We found that ts-patch demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.