ts-node
TypeScript execution and REPL for node.js
README
TypeScript Node
TypeScript execution and REPL for node.js, with source map support. Works with typescript@>=2.7.
Experimental ESM support
Native ESM support is currently experimental. For usage, limitations, and to provide feedback, see #1007.
Installation
- ```sh
- # Locally in your project.
- npm install -D typescript
- npm install -D ts-node
- # Or globally with TypeScript.
- npm install -g typescript
- npm install -g ts-node
- ```
Tip: Installing modules locally allows you to control and share the versions through package.json. TS Node will always resolve the compiler from cwd before checking relative to its own installation.
Usage
Shell
- ```sh
- # Execute a script as `node` + `tsc`.
- ts-node script.ts
- # Starts a TypeScript REPL.
- ts-node
- # Execute code with TypeScript.
- ts-node -e 'console.log("Hello, world!")'
- # Execute, and print, code with TypeScript.
- ts-node -p -e '"Hello, world!"'
- # Pipe scripts to execute with TypeScript.
- echo 'console.log("Hello, world!")' | ts-node
- # Equivalent to ts-node --cwd-mode
- ts-node-cwd scripts.ts
- # Equivalent to ts-node --transpile-only
- ts-node-transpile-only scripts.ts
- ```
Shebang
- ```typescript
- #!/usr/bin/env ts-node
- console.log("Hello, world!")
- ```
Passing CLI arguments via shebang is allowed on Mac but not Linux. For example, the following will fail on Linux:
- ```
- #!/usr/bin/env ts-node --transpile-only --files
- // This shebang is not portable. It only works on Mac
- ```
Programmatic
You can require ts-node and register the loader for future requires by using `require('ts-node').register({ / options / }). You can also use file shortcuts - node -r ts-node/register or node -r ts-node/register/transpile-only` - depending on your preferences.
Note: If you need to use advanced node.js CLI arguments (e.g. --inspect), use them with node -r ts-node/register instead of the ts-node CLI.
Developers
TS Node exports a create() function that can be used to initialize a TypeScript compiler that isn't registered to require.extensions, and it uses the same code as register.
Mocha
Mocha 6
- ```sh
- mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
- ```
Note: --watch-extensions is only used in --watch mode.
Mocha 7
- ```sh
- mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'tests/**/*.{ts,tsx}' [...args]
- ```
Tape
- ```sh
- ts-node node_modules/tape/bin/tape [...args]
- ```
Gulp
- ```sh
- # Create a `gulpfile.ts` and run `gulp`.
- gulp
- ```