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


  1. ```sh
  2. # Locally in your project.
  3. npm install -D typescript
  4. npm install -D ts-node

  5. # Or globally with TypeScript.
  6. npm install -g typescript
  7. npm install -g ts-node
  8. ```

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


  1. ```sh
  2. # Execute a script as `node` + `tsc`.
  3. ts-node script.ts

  4. # Starts a TypeScript REPL.
  5. ts-node

  6. # Execute code with TypeScript.
  7. ts-node -e 'console.log("Hello, world!")'

  8. # Execute, and print, code with TypeScript.
  9. ts-node -p -e '"Hello, world!"'

  10. # Pipe scripts to execute with TypeScript.
  11. echo 'console.log("Hello, world!")' | ts-node

  12. # Equivalent to ts-node --cwd-mode
  13. ts-node-cwd scripts.ts

  14. # Equivalent to ts-node --transpile-only
  15. ts-node-transpile-only scripts.ts
  16. ```

TypeScript REPL

Shebang


  1. ```typescript
  2. #!/usr/bin/env ts-node

  3. console.log("Hello, world!")
  4. ```

Passing CLI arguments via shebang is allowed on Mac but not Linux.  For example, the following will fail on Linux:

  1. ```
  2. #!/usr/bin/env ts-node --transpile-only --files
  3. // This shebang is not portable.  It only works on Mac
  4. ```

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

  1. ```sh
  2. mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
  3. ```

Note: --watch-extensions is only used in --watch mode.

Mocha 7

  1. ```sh
  2. mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'tests/**/*.{ts,tsx}' [...args]
  3. ```

Tape


  1. ```sh
  2. ts-node node_modules/tape/bin/tape [...args]
  3. ```

Gulp


  1. ```sh
  2. # Create a `gulpfile.ts` and run `gulp`.
  3. gulp
  4. ```