ts-node is a TypeScript execution engine for Node.js. It allows you to run your TypeScript code directly without precompiling your TypeScript code to JavaScript. ts-node transforms TypeScript to JavaScript in-memory without writing it to disk.
Large projects may still take some time to process. This is where SWC comes handy. SWC is a TypeScript-compatible transpiler written in Rust. This makes the processing of TypeScript code faster than the vanilla TypeScript compiler.
This tutorial shows you how to run your TypeScript code using ts-node with SWC.
TypeScript Series Overview
- How to Export Transpiled Code From package.json
- Use Nodemon to Restart Your Server on Changes
- How to Allow Trailing Commas (Comma-Dangle) With Typescript-ESLint
- Use SWC to Speed up TypeScript Code
- Fixing Null Type Ignored in Union Type
- How to Remove Index Signature from a Type
- Module Augmentation Overwrites Declarations Instead of Merging Them
- Get All Keys of an Enum
- Get All Values of an Enum
- Using a String as Enum Key
- Understanding “keyof typeof”
- Get Type of Class Properties and Omit Methods
Running TypeScript with ts-node and SWC
You can run your TypeScript code with ts-node and tell it to use SWC for compilation.
Installing SWC Dependencies
In modern code bases you must install @swc/core
as a project dependency. You can install it using NPM:
npm i -D @swc/core
In case your TypeScript target
is below es2015
and you’re using async/await or generator function you must also install the regenerator-runtime
package:
npm i -D @swc/core regenerator-runtime
Use ts-node with SWC
You can use the --swc
flag in case ts-node is globally available on your machine. Append that flag and run the TypeScript file:
ts-node --swc server.ts
You may also configure ts-node to use SWC in your tsconfig.json
file. Specify a ts-node
object at the root of your tsconfig.json
and tell it to use SWC:
{
"ts-node": {
"swc": true
}
}
Use @swc/helpers Instead of TypeScript’s „importHelpers“
TypeScript provides importHelpers for downleveling operations. You can also replace the import helpers with SWC helpers. You must install the @swc/helpers
package if importHelpers
are enabled in your project:
npm i -D @swc/helpers
SWC uses @swc/helpers
instead of tslib
bringing some more speed improvements.
Enjoy running your TypeScript code with speed!