nonara / ts-patch

Augment the TypeScript compiler to support extended functionality
MIT License
762 stars 26 forks source link

[How To] Use with `tsx` runner #148

Open joliss opened 8 months ago

joliss commented 8 months ago

I'm using tsx, a ts-node alternative for running .ts files with Node. Is there a some way to run ts-patch projects with tsx?

cmidgley commented 3 months ago

For those interested in tsx with ts-patch, I have it working with my transformers. The reason it doesn't "just work" is because tsx uses esbuild, which means it does not call the typescript compiler API's that ts-patch modifies.

The trick is to get it to load your transformer before tsx so the input to esbuild is the output from your transformer. To do this, you need to use the node cli and not tsx, since once it starts running it will go directly to esbuild and never call your transformer.

For example, with modern register-based transformers (and having previously used ts-patch install):

node --import yourTransformer --import tsx myFile.ts

or this for legacy loader-based transformers:

node --loader yourTransformer --import tsx myFile.ts

This will cause your transformer to load before tsx, allowing the files to be processed by it before sending on to tsx and esbuild.

Also, if you have custom tsconfig.json file, you can specify that with the environment variable TSX_CONFIG_PATH

TSX_CONFIG_PATH=tsconfig.different.json node --import yourTransformer --import tsx myFile.ts

I have this all working with node 22.3.0, ts-patch 3.2.1, typescript 5.5.3 and tsx 4.16.2.