UNPKG

48.8 kBMarkdownView Raw
1<!--
2BEFORE EDITING THIS README
3Our README.md is auto-generated by combining pages in website/docs and website/readme-sources
4
5If you are sending a pull request to improve documentation, submit your changes
6in the source markdown files and we will generate the README from there.
7
8You can build the readme with this command:
9
10 cd website && yarn build-readme
11-->
12
13# [![TypeScript Node](logo.svg?sanitize=true)](https://typestrong.org/ts-node)
14
15[![NPM version](https://img.shields.io/npm/v/ts-node.svg?style=flat)](https://npmjs.org/package/ts-node)
16[![NPM downloads](https://img.shields.io/npm/dm/ts-node.svg?style=flat)](https://npmjs.org/package/ts-node)
17[![Build status](https://img.shields.io/github/workflow/status/TypeStrong/ts-node/Continuous%20Integration)](https://github.com/TypeStrong/ts-node/actions?query=workflow%3A%22Continuous+Integration%22)
18[![Test coverage](https://codecov.io/gh/TypeStrong/ts-node/branch/main/graph/badge.svg)](https://codecov.io/gh/TypeStrong/ts-node)
19
20> TypeScript execution and REPL for node.js, with source map and native ESM support.
21
22The latest documentation can also be found on our website: <https://typestrong.org/ts-node>
23
24# Table of Contents
25
26* [Overview](#overview)
27 * [Features](#features)
28* [Installation](#installation)
29* [Usage](#usage)
30 * [Command Line](#command-line)
31 * [Shebang](#shebang)
32 * [node flags and other tools](#node-flags-and-other-tools)
33 * [Programmatic](#programmatic)
34* [Configuration](#configuration)
35 * [CLI flags](#cli-flags)
36 * [Via tsconfig.json (recommended)](#via-tsconfigjson-recommended)
37 * [@tsconfig/bases](#tsconfigbases)
38 * [Default config](#default-config)
39 * [`node` flags](#node-flags)
40* [Options](#options)
41 * [CLI Options](#cli-options)
42 * [help](#help)
43 * [version](#version)
44 * [eval](#eval)
45 * [print](#print)
46 * [interactive](#interactive)
47 * [esm](#esm)
48 * [TSConfig Options](#tsconfig-options)
49 * [project](#project)
50 * [skipProject](#skipproject)
51 * [cwdMode](#cwdmode)
52 * [compilerOptions](#compileroptions)
53 * [showConfig](#showconfig)
54 * [Typechecking](#typechecking)
55 * [transpileOnly](#transpileonly)
56 * [typeCheck](#typecheck)
57 * [compilerHost](#compilerhost)
58 * [files](#files)
59 * [ignoreDiagnostics](#ignorediagnostics)
60 * [Transpilation Options](#transpilation-options)
61 * [ignore](#ignore)
62 * [skipIgnore](#skipignore)
63 * [compiler](#compiler)
64 * [swc](#swc)
65 * [transpiler](#transpiler)
66 * [preferTsExts](#prefertsexts)
67 * [Diagnostic Options](#diagnostic-options)
68 * [logError](#logerror)
69 * [pretty](#pretty)
70 * [TS_NODE_DEBUG](#ts_node_debug)
71 * [Advanced Options](#advanced-options)
72 * [require](#require)
73 * [cwd](#cwd)
74 * [emit](#emit)
75 * [scope](#scope)
76 * [scopeDir](#scopedir)
77 * [moduleTypes](#moduletypes)
78 * [TS_NODE_HISTORY](#ts_node_history)
79 * [noExperimentalReplAwait](#noexperimentalreplawait)
80 * [experimentalResolver](#experimentalresolver)
81 * [experimentalSpecifierResolution](#experimentalspecifierresolution)
82 * [API Options](#api-options)
83* [SWC](#swc-1)
84* [CommonJS vs native ECMAScript modules](#commonjs-vs-native-ecmascript-modules)
85 * [CommonJS](#commonjs)
86 * [Native ECMAScript modules](#native-ecmascript-modules)
87* [Troubleshooting](#troubleshooting)
88 * [Configuration](#configuration-1)
89 * [Common errors](#common-errors)
90 * [`TSError`](#tserror)
91 * [`SyntaxError`](#syntaxerror)
92 * [Unsupported JavaScript syntax](#unsupported-javascript-syntax)
93 * [`ERR_REQUIRE_ESM`](#err_require_esm)
94 * [`ERR_UNKNOWN_FILE_EXTENSION`](#err_unknown_file_extension)
95 * [Missing Types](#missing-types)
96 * [npx, yarn dlx, and node_modules](#npx-yarn-dlx-and-node_modules)
97* [Performance](#performance)
98 * [Skip typechecking](#skip-typechecking)
99 * [With typechecking](#with-typechecking)
100* [Advanced](#advanced)
101 * [How it works](#how-it-works)
102 * [Ignored files](#ignored-files)
103 * [File extensions](#file-extensions)
104 * [Skipping `node_modules`](#skipping-node_modules)
105 * [Skipping pre-compiled TypeScript](#skipping-pre-compiled-typescript)
106 * [Scope by directory](#scope-by-directory)
107 * [Ignore by regexp](#ignore-by-regexp)
108 * [paths and baseUrl
109 ](#paths-and-baseurl)
110 * [Why is this not built-in to ts-node?](#why-is-this-not-built-in-to-ts-node)
111 * [Third-party compilers](#third-party-compilers)
112 * [Transpilers](#transpilers)
113 * [Third-party plugins](#third-party-plugins)
114 * [Write your own plugin](#write-your-own-plugin)
115 * [Module type overrides](#module-type-overrides)
116 * [Caveats](#caveats)
117 * [API](#api)
118* [Recipes](#recipes)
119 * [Watching and restarting](#watching-and-restarting)
120 * [AVA](#ava)
121 * [CommonJS](#commonjs-1)
122 * [Native ECMAScript modules](#native-ecmascript-modules-1)
123 * [Gulp](#gulp)
124 * [IntelliJ and Webstorm](#intellij-and-webstorm)
125 * [Mocha](#mocha)
126 * [Mocha 7 and newer](#mocha-7-and-newer)
127 * [Mocha <=6](#mocha-6)
128 * [Tape](#tape)
129 * [Visual Studio Code](#visual-studio-code)
130 * [Other](#other)
131* [License](#license)
132
133# Overview
134
135ts-node is a TypeScript execution engine and REPL for Node.js.
136
137It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling.
138This is accomplished by hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.js
139tools and libraries.
140
141## Features
142
143* Automatic sourcemaps in stack traces
144* Automatic `tsconfig.json` parsing
145* Automatic defaults to match your node version
146* Typechecking (optional)
147* REPL
148* Write standalone scripts
149* Native ESM loader
150* Use third-party transpilers
151* Use custom transformers
152* Integrate with test runners, debuggers, and CLI tools
153* Compatible with pre-compilation for production
154
155![TypeScript REPL](website/static/img/screenshot.png)
156
157# Installation
158
159```shell
160# Locally in your project.
161npm install -D typescript
162npm install -D ts-node
163
164# Or globally with TypeScript.
165npm install -g typescript
166npm install -g ts-node
167
168# Depending on configuration, you may also need these
169npm install -D tslib @types/node
170```
171
172**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.
173
174# Usage
175
176## Command Line
177
178```shell
179# Execute a script as `node` + `tsc`.
180ts-node script.ts
181
182# Starts a TypeScript REPL.
183ts-node
184
185# Execute code with TypeScript.
186ts-node -e 'console.log("Hello, world!")'
187
188# Execute, and print, code with TypeScript.
189ts-node -p -e '"Hello, world!"'
190
191# Pipe scripts to execute with TypeScript.
192echo 'console.log("Hello, world!")' | ts-node
193
194# Equivalent to ts-node --transpileOnly
195ts-node-transpile-only script.ts
196
197# Equivalent to ts-node --cwdMode
198ts-node-cwd script.ts
199
200# Equivalent to ts-node --esm
201ts-node-esm script.ts
202```
203
204## Shebang
205
206To write scripts with maximum portability, [specify options in your `tsconfig.json`](#via-tsconfigjson-recommended) and omit them from the shebang.
207
208```typescript twoslash
209#!/usr/bin/env ts-node
210
211// ts-node options are read from tsconfig.json
212
213console.log("Hello, world!")
214```
215
216Including options within the shebang requires the [`env -S` flag](https://manpages.debian.org/bullseye/coreutils/env.1.en.html#S), which is available on recent versions of `env`. ([compatibility](https://github.com/TypeStrong/ts-node/pull/1448#issuecomment-913895766))
217
218```typescript twoslash
219#!/usr/bin/env -S ts-node --files
220// This shebang works on Mac and Linux with newer versions of env
221// Technically, Mac allows omitting `-S`, but Linux requires it
222```
223
224To test your version of `env` for compatibility with `-S`:
225
226```shell
227# Note that these unusual quotes are necessary
228/usr/bin/env --debug '-S echo foo bar'
229```
230
231## node flags and other tools
232
233You can register ts-node without using our CLI: `node -r ts-node/register` and `node --loader ts-node/esm`
234
235In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads. This can be combined with other node flags.
236
237```shell
238NODE_OPTIONS="-r ts-node/register --no-warnings" node ./index.ts
239```
240
241Or, if you require native ESM support:
242
243```shell
244NODE_OPTIONS="--loader ts-node/esm"
245```
246
247This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code.
248
249If you are invoking node directly, you can avoid the environment variable and pass those flags to node.
250
251```shell
252node --loader ts-node/esm --inspect ./index.ts
253```
254
255## Programmatic
256
257You can require ts-node and register the loader for future requires by using `require('ts-node').register({ /* options */ })`.
258
259Check out our [API](#api) for more features.
260
261# Configuration
262
263ts-node supports a variety of options which can be specified via `tsconfig.json`, as CLI flags, as environment variables, or programmatically.
264
265For a complete list, see [Options](#options).
266
267## CLI flags
268
269ts-node CLI flags must come *before* the entrypoint script. For example:
270
271```shell
272$ ts-node --project tsconfig-dev.json say-hello.ts Ronald
273Hello, Ronald!
274```
275
276## Via tsconfig.json (recommended)
277
278ts-node automatically finds and loads `tsconfig.json`. Most ts-node options can be specified in a `"ts-node"` object using their programmatic, camelCase names. We recommend this because it works even when you cannot pass CLI flags, such as `node --require ts-node/register` and when using shebangs.
279
280Use `--skipProject` to skip loading the `tsconfig.json`. Use `--project` to explicitly specify the path to a `tsconfig.json`.
281
282When searching, it is resolved using [the same search behavior as `tsc`](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html). By default, this search is performed relative to the entrypoint script. In `--cwdMode` or if no entrypoint is specified -- for example when using the REPL -- the search is performed relative to `--cwd` / `process.cwd()`.
283
284You can use this sample configuration as a starting point:
285
286```jsonc title="tsconfig.json"
287{
288 // This is an alias to @tsconfig/node16: https://github.com/tsconfig/bases
289 "extends": "ts-node/node16/tsconfig.json",
290
291 // Most ts-node options can be specified here using their programmatic names.
292 "ts-node": {
293 // It is faster to skip typechecking.
294 // Remove if you want ts-node to do typechecking.
295 "transpileOnly": true,
296
297 "files": true,
298
299 "compilerOptions": {
300 // compilerOptions specified here will override those declared below,
301 // but *only* in ts-node. Useful if you want ts-node and tsc to use
302 // different options with a single tsconfig.json.
303 }
304 },
305 "compilerOptions": {
306 // typescript options here
307 }
308}
309```
310
311Our bundled [JSON schema](https://unpkg.com/browse/ts-node@latest/tsconfig.schema.json) lists all compatible options.
312
313### @tsconfig/bases
314
315[@tsconfig/bases](https://github.com/tsconfig/bases) maintains recommended configurations for several node versions.
316As a convenience, these are bundled with ts-node.
317
318```jsonc title="tsconfig.json"
319{
320 "extends": "ts-node/node16/tsconfig.json",
321
322 // Or install directly with `npm i -D @tsconfig/node16`
323 "extends": "@tsconfig/node16/tsconfig.json",
324}
325```
326
327### Default config
328
329If no `tsconfig.json` is loaded from disk, ts-node will use the newest recommended defaults from
330[@tsconfig/bases](https://github.com/tsconfig/bases/) compatible with your `node` and `typescript` versions.
331With the latest `node` and `typescript`, this is [`@tsconfig/node16`](https://github.com/tsconfig/bases/blob/master/bases/node16.json).
332
333Older versions of `typescript` are incompatible with `@tsconfig/node16`. In those cases we will use an older default configuration.
334
335When in doubt, `ts-node --showConfig` will log the configuration being used, and `ts-node -vv` will log `node` and `typescript` versions.
336
337## `node` flags
338
339[`node` flags](https://nodejs.org/api/cli.html) must be passed directly to `node`; they cannot be passed to the ts-node binary nor can they be specified in `tsconfig.json`
340
341We recommend using the [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) environment variable to pass options to `node`.
342
343```shell
344NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts
345```
346
347Alternatively, you can invoke `node` directly and install ts-node via `--require`/`-r`
348
349```shell
350node --trace-deprecation --abort-on-uncaught-exception -r ts-node/register ./index.ts
351```
352
353# Options
354
355All command-line flags support both `--camelCase` and `--hyphen-case`.
356
357Most options can be declared in your tsconfig.json: [Configuration via tsconfig.json](#via-tsconfigjson-recommended)
358
359`ts-node` supports `--print` (`-p`), `--eval` (`-e`), `--require` (`-r`) and `--interactive` (`-i`) similar to the [node.js CLI](https://nodejs.org/api/cli.html).
360
361`ts-node` supports `--project` and `--showConfig` similar to the [tsc CLI](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options).
362
363*Environment variables, where available, are in `ALL_CAPS`*
364
365## CLI Options
366
367### help
368
369```shell
370ts-node --help
371```
372
373Prints the help text
374
375### version
376
377```shell
378ts-node -v
379ts-node -vvv
380```
381
382Prints the version. `-vv` includes node and typescript compiler versions. `-vvv` includes absolute paths to ts-node and
383typescript installations.
384
385### eval
386
387```shell
388ts-node -e <typescript code>
389# Example
390ts-node -e 'console.log("Hello world!")'
391```
392
393Evaluate code
394
395### print
396
397```shell
398ts-node -p -e <typescript code>
399# Example
400ts-node -p -e '"Hello world!"'
401```
402
403Print result of `--eval`
404
405### interactive
406
407```shell
408ts-node -i
409```
410
411Opens the REPL even if stdin does not appear to be a terminal
412
413### esm
414
415```shell
416ts-node --esm
417ts-node-esm
418```
419
420Bootstrap with the ESM loader, enabling full ESM support
421
422## TSConfig Options
423
424### project
425
426```shell
427ts-node -P <path/to/tsconfig>
428ts-node --project <path/to/tsconfig>
429```
430
431Path to tsconfig file.
432
433*Note the uppercase `-P`. This is different from `tsc`'s `-p/--project` option.*
434
435*Environment:* `TS_NODE_PROJECT`
436
437### skipProject
438
439```shell
440ts-node --skipProject
441```
442
443Skip project config resolution and loading
444
445*Default:* `false` <br/>
446*Environment:* `TS_NODE_SKIP_PROJECT`
447
448### cwdMode
449
450```shell
451ts-node -c
452ts-node --cwdMode
453ts-node-cwd
454```
455
456Resolve config relative to the current directory instead of the directory of the entrypoint script
457
458### compilerOptions
459
460```shell
461ts-node -O <json compilerOptions>
462ts-node --compilerOptions <json compilerOptions>
463```
464
465JSON object to merge with compiler options
466
467*Environment:* `TS_NODE_COMPILER_OPTIONS`
468
469### showConfig
470
471```shell
472ts-node --showConfig
473```
474
475Print resolved `tsconfig.json`, including `ts-node` options, and exit
476
477## Typechecking
478
479### transpileOnly
480
481```shell
482ts-node -T
483ts-node --transpileOnly
484```
485
486Use TypeScript's faster `transpileModule`
487
488*Default:* `false`<br/>
489*Environment:* `TS_NODE_TRANSPILE_ONLY`
490
491### typeCheck
492
493```shell
494ts-node --typeCheck
495```
496
497Opposite of `--transpileOnly`
498
499*Default:* `true`<br/>
500*Environment:* `TS_NODE_TYPE_CHECK`
501
502### compilerHost
503
504```shell
505ts-node -H
506ts-node --compilerHost
507```
508
509Use TypeScript's compiler host API
510
511*Default:* `false` <br/>
512*Environment:* `TS_NODE_COMPILER_HOST`
513
514### files
515
516```shell
517ts-node --files
518```
519
520Load `files`, `include` and `exclude` from `tsconfig.json` on startup. This may
521avoid certain typechecking failures. See [Missing types](#missing-types) for details.
522
523*Default:* `false` <br/>
524*Environment:* `TS_NODE_FILES`
525
526### ignoreDiagnostics
527
528```shell
529ts-node -D <code,code>
530ts-node --ignoreDiagnostics <code,code>
531```
532
533Ignore TypeScript warnings by diagnostic code
534
535*Environment:* `TS_NODE_IGNORE_DIAGNOSTICS`
536
537## Transpilation Options
538
539### ignore
540
541```shell
542ts-node -I <regexp matching ignored files>
543ts-node --ignore <regexp matching ignored files>
544```
545
546Override the path patterns to skip compilation
547
548*Default:* `/node_modules/` <br/>
549*Environment:* `TS_NODE_IGNORE`
550
551### skipIgnore
552
553```shell
554ts-node --skipIgnore
555```
556
557Skip ignore checks
558
559*Default:* `false` <br/>
560*Environment:* `TS_NODE_SKIP_IGNORE`
561
562### compiler
563
564```shell
565ts-node -C <name>
566ts-node --compiler <name>
567```
568
569Specify a custom TypeScript compiler
570
571*Default:* `typescript` <br/>
572*Environment:* `TS_NODE_COMPILER`
573
574### swc
575
576```shell
577ts-node --swc
578```
579
580Transpile with [swc](#swc). Implies `--transpileOnly`
581
582*Default:* `false`
583
584### transpiler
585
586```shell
587ts-node --transpiler <name>
588# Example
589ts-node --transpiler ts-node/transpilers/swc
590```
591
592Use a third-party, non-typechecking transpiler
593
594### preferTsExts
595
596```shell
597ts-node --preferTsExts
598```
599
600Re-order file extensions so that TypeScript imports are preferred
601
602*Default:* `false` <br/>
603*Environment:* `TS_NODE_PREFER_TS_EXTS`
604
605## Diagnostic Options
606
607### logError
608
609```shell
610ts-node --logError
611```
612
613Logs TypeScript errors to stderr instead of throwing exceptions
614
615*Default:* `false` <br/>
616*Environment:* `TS_NODE_LOG_ERROR`
617
618### pretty
619
620```shell
621ts-node --pretty
622```
623
624Use pretty diagnostic formatter
625
626*Default:* `false` <br/>
627*Environment:* `TS_NODE_PRETTY`
628
629### TS_NODE_DEBUG
630
631```shell
632TS_NODE_DEBUG=true ts-node
633```
634
635Enable debug logging
636
637## Advanced Options
638
639### require
640
641```shell
642ts-node -r <module name or path>
643ts-node --require <module name or path>
644```
645
646Require a node module before execution
647
648### cwd
649
650```shell
651ts-node --cwd <path/to/directory>
652```
653
654Behave as if invoked in this working directory
655
656*Default:* `process.cwd()`<br/>
657*Environment:* `TS_NODE_CWD`
658
659### emit
660
661```shell
662ts-node --emit
663```
664
665Emit output files into `.ts-node` directory. Requires `--compilerHost`
666
667*Default:* `false` <br/>
668*Environment:* `TS_NODE_EMIT`
669
670### scope
671
672```shell
673ts-node --scope
674```
675
676Scope compiler to files within `scopeDir`. Anything outside this directory is ignored.
677
678*Default:* `false` <br/>
679*Environment:* `TS_NODE_SCOPE`
680
681### scopeDir
682
683```shell
684ts-node --scopeDir <path/to/directory>
685```
686
687Directory within which compiler is limited when `scope` is enabled.
688
689*Default:* First of: `tsconfig.json` "rootDir" if specified, directory containing `tsconfig.json`, or cwd if no `tsconfig.json` is loaded.<br/>
690*Environment:* `TS_NODE_SCOPE_DIR`
691
692### moduleTypes
693
694Override the module type of certain files, ignoring the `package.json` `"type"` field. See [Module type overrides](#module-type-overrides) for details.
695
696*Default:* obeys `package.json` `"type"` and `tsconfig.json` `"module"` <br/>
697*Can only be specified via `tsconfig.json` or API.*
698
699### TS_NODE_HISTORY
700
701```shell
702TS_NODE_HISTORY=<path/to/history/file> ts-node
703```
704
705Path to history file for REPL
706
707*Default:* `~/.ts_node_repl_history`
708
709### noExperimentalReplAwait
710
711```shell
712ts-node --noExperimentalReplAwait
713```
714
715Disable top-level await in REPL. Equivalent to node's [`--no-experimental-repl-await`](https://nodejs.org/api/cli.html#cli_no_experimental_repl_await)
716
717*Default:* Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.<br/>
718*Environment:* `TS_NODE_EXPERIMENTAL_REPL_AWAIT` set `false` to disable
719
720### experimentalResolver
721
722Enable experimental hooks that re-map imports and require calls to support:
723
724* remapping extensions, e.g. so that `import "./foo.js"` will execute `foo.ts`. Currently the following extensions will be mapped:
725 * `.js` to `.ts`, `.tsx`, or `.jsx`
726 * `.cjs` to `.cts`
727 * `.mjs` to `.mts`
728 * `.jsx` to `.tsx`
729* including file extensions in CommonJS, for consistency with ESM where this is often mandatory
730
731In the future, this hook will also support:
732
733* `baseUrl`, `paths`
734* `rootDirs`
735* `outDir` to `rootDir` mappings for composite projects and monorepos
736
737For details, see [#1514](https://github.com/TypeStrong/ts-node/issues/1514).
738
739*Default:* `false`, but will likely be enabled by default in a future version<br/>
740*Can only be specified via `tsconfig.json` or API.*
741
742### experimentalSpecifierResolution
743
744```shell
745ts-node --experimentalSpecifierResolution node
746```
747
748Like node's [`--experimental-specifier-resolution`](https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#customizing-esm-specifier-resolution-algorithm), but can also be set in your `tsconfig.json` for convenience.
749Requires [`esm`](#esm) to be enabled.
750
751*Default:* `explicit`<br/>
752
753## API Options
754
755The API includes [additional options](https://typestrong.org/ts-node/api/interfaces/RegisterOptions.html) not shown here.
756
757# SWC
758
759SWC support is built-in via the `--swc` flag or `"swc": true` tsconfig option.
760
761[SWC](https://swc.rs) is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster than vanilla `transpileOnly`.
762
763To use it, first install `@swc/core` or `@swc/wasm`. If using `importHelpers`, also install `@swc/helpers`. If `target` is less than "es2015" and using `async`/`await` or generator functions, also install `regenerator-runtime`.
764
765```shell
766npm i -D @swc/core @swc/helpers regenerator-runtime
767```
768
769Then add the following to your `tsconfig.json`.
770
771```jsonc title="tsconfig.json"
772{
773 "ts-node": {
774 "swc": true
775 }
776}
777```
778
779> SWC uses `@swc/helpers` instead of `tslib`. If you have enabled `importHelpers`, you must also install `@swc/helpers`.
780
781# CommonJS vs native ECMAScript modules
782
783TypeScript is almost always written using modern `import` syntax, but it is also transformed before being executed by the underlying runtime. You can choose to either transform to CommonJS or to preserve the native `import` syntax, using node's native ESM support. Configuration is different for each.
784
785Here is a brief comparison of the two.
786
787| CommonJS | Native ECMAScript modules |
788|---|---|
789| Write native `import` syntax | Write native `import` syntax |
790| Transforms `import` into `require()` | Does not transform `import` |
791| Node executes scripts using the classic [CommonJS loader](https://nodejs.org/dist/latest-v16.x/docs/api/modules.html) | Node executes scripts using the new [ESM loader](https://nodejs.org/dist/latest-v16.x/docs/api/esm.html) |
792| Use any of:<br/>`ts-node`<br/>`node -r ts-node/register`<br/>`NODE_OPTIONS="ts-node/register" node`<br/>`require('ts-node').register({/* options */})` | Use any of:<br/>`ts-node --esm`<br/>`ts-node-esm`<br/>Set `"esm": true` in `tsconfig.json`<br />`node --loader ts-node/esm`<br/>`NODE_OPTIONS="--loader ts-node/esm" node` |
793
794## CommonJS
795
796Transforming to CommonJS is typically simpler and more widely supported because it is older. You must remove [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) from `package.json` and set [`"module": "CommonJS"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`.
797
798```jsonc title="package.json"
799{
800 // This can be omitted; commonjs is the default
801 "type": "commonjs"
802}
803```
804
805```jsonc title="tsconfig.json"
806{
807 "compilerOptions": {
808 "module": "CommonJS"
809 }
810}
811```
812
813If you must keep `"module": "ESNext"` for `tsc`, webpack, or another build tool, you can set an override for ts-node.
814
815```jsonc title="tsconfig.json"
816{
817 "compilerOptions": {
818 "module": "ESNext"
819 },
820 "ts-node": {
821 "compilerOptions": {
822 "module": "CommonJS"
823 }
824 }
825}
826```
827
828## Native ECMAScript modules
829
830[Node's ESM loader hooks](https://nodejs.org/api/esm.html#esm_experimental_loaders) are [**experimental**](https://nodejs.org/api/documentation.html#documentation_stability_index) and subject to change. ts-node's ESM support is as stable as possible, but it relies on APIs which node can *and will* break in new versions of node. Thus it is not recommended for production.
831
832For complete usage, limitations, and to provide feedback, see [#1007](https://github.com/TypeStrong/ts-node/issues/1007).
833
834You must set [`"type": "module"`](https://nodejs.org/api/packages.html#packages_type) in `package.json` and [`"module": "ESNext"`](https://www.typescriptlang.org/tsconfig/#module) in `tsconfig.json`.
835
836```jsonc title="package.json"
837{
838 "type": "module"
839}
840```
841
842```jsonc title="tsconfig.json"
843{
844 "compilerOptions": {
845 "module": "ESNext" // or ES2015, ES2020
846 },
847 "ts-node": {
848 // Tell ts-node CLI to install the --loader automatically, explained below
849 "esm": true
850 }
851}
852```
853
854You must also ensure node is passed `--loader`. The ts-node CLI will do this automatically with our `esm` option.
855
856> Note: `--esm` must spawn a child process to pass it `--loader`. This may change if node adds the ability to install loader hooks
857> into the current process.
858
859```shell
860# pass the flag
861ts-node --esm
862# Use the convenience binary
863ts-node-esm
864# or add `"esm": true` to your tsconfig.json to make it automatic
865ts-node
866```
867
868If you are not using our CLI, pass the loader flag to node.
869
870```shell
871node --loader ts-node/esm ./index.ts
872# Or via environment variable
873NODE_OPTIONS="--loader ts-node/esm" node ./index.ts
874```
875
876# Troubleshooting
877
878## Configuration
879
880ts-node uses sensible default configurations to reduce boilerplate while still respecting `tsconfig.json` if you
881have one. If you are unsure which configuration is used, you can log it with `ts-node --showConfig`. This is similar to
882`tsc --showConfig` but includes `"ts-node"` options as well.
883
884ts-node also respects your locally-installed `typescript` version, but global installations fallback to the globally-installed
885`typescript`. If you are unsure which versions are used, `ts-node -vv` will log them.
886
887```shell
888$ ts-node -vv
889ts-node v10.0.0
890node v16.1.0
891compiler v4.2.2
892
893$ ts-node --showConfig
894{
895 "compilerOptions": {
896 "target": "es6",
897 "lib": [
898 "es6",
899 "dom"
900 ],
901 "rootDir": "./src",
902 "outDir": "./.ts-node",
903 "module": "commonjs",
904 "moduleResolution": "node",
905 "strict": true,
906 "declaration": false,
907 "sourceMap": true,
908 "inlineSources": true,
909 "types": [
910 "node"
911 ],
912 "stripInternal": true,
913 "incremental": true,
914 "skipLibCheck": true,
915 "importsNotUsedAsValues": "error",
916 "inlineSourceMap": false,
917 "noEmit": false
918 },
919 "ts-node": {
920 "cwd": "/d/project",
921 "projectSearchDir": "/d/project",
922 "require": [],
923 "project": "/d/project/tsconfig.json"
924 }
925}
926```
927
928## Common errors
929
930It is important to differentiate between errors from ts-node, errors from the TypeScript compiler, and errors from `node`. It is also important to understand when errors are caused by a type error in your code, a bug in your code, or a flaw in your configuration.
931
932### `TSError`
933
934Type errors from the compiler are thrown as a `TSError`. These are the same as errors you get from `tsc`.
935
936### `SyntaxError`
937
938Any error that is not a `TSError` is from node.js (e.g. `SyntaxError`), and cannot be fixed by TypeScript or ts-node. These are bugs in your code or configuration.
939
940#### Unsupported JavaScript syntax
941
942Your version of `node` may not support all JavaScript syntax supported by TypeScript. The compiler must transform this syntax via "downleveling," which is controlled by
943the [tsconfig `"target"` option](https://www.typescriptlang.org/tsconfig#target). Otherwise your code will compile fine, but node will throw a `SyntaxError`.
944
945For example, `node` 12 does not understand the `?.` optional chaining operator. If you use `"target": "esnext"`, then the following TypeScript syntax:
946
947```typescript twoslash
948const bar: string | undefined = foo?.bar;
949```
950
951will compile into this JavaScript:
952
953```javascript
954const a = foo?.bar;
955```
956
957When you try to run this code, node 12 will throw a `SyntaxError`. To fix this, you must switch to `"target": "es2019"` or lower so TypeScript transforms `?.` into something `node` can understand.
958
959### `ERR_REQUIRE_ESM`
960
961This error is thrown by node when a module is `require()`d, but node believes it should execute as native ESM. This can happen for a few reasons:
962
963* You have installed an ESM dependency but your own code compiles to CommonJS.
964 * Solution: configure your project to compile and execute as native ESM. [Docs](#native-ecmascript-modules)
965 * Solution: downgrade the dependency to an older, CommonJS version.
966* You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS -->
967 * Solution: if supported by the relevant tool, rename your config file to `.cts`
968 * Solution: Configure a module type override. [Docs](#module-type-overrides)
969* You have a mix of CommonJS and native ESM in your project
970 * Solution: double-check all package.json "type" and tsconfig.json "module" configuration [Docs](#commonjs-vs-native-ecmascript-modules)
971 * Solution: consider simplifying by making your project entirely CommonJS or entirely native ESM
972
973### `ERR_UNKNOWN_FILE_EXTENSION`
974
975This error is thrown by node when a module has an unrecognized file extension, or no extension at all, and is being executed as native ESM. This can happen for a few reasons:
976
977* You are using a tool which has an extensionless binary, such as `mocha`.
978 * CommonJS supports extensionless files but native ESM does not.
979 * Solution: upgrade to ts-node >=[v10.6.0](https://github.com/TypeStrong/ts-node/releases/tag/v10.6.0), which implements a workaround.
980* Our ESM loader is not installed.
981 * Solution: Use `ts-node-esm`, `ts-node --esm`, or add `"ts-node": {"esm": true}` to your tsconfig.json. [Docs](#native-ecmascript-modules)
982* You have moved your project to ESM but still have a config file, such as `webpack.config.ts`, which must be executed as CommonJS <!-- SYNC_WITH_MTO_DOCS -->
983 * Solution: if supported by the relevant tool, rename your config file to `.cts`
984 * Solution: Configure a module type override. [Docs](#module-type-overrides)
985
986## Missing Types
987
988ts-node does *not* eagerly load `files`, `include` or `exclude` by default. This is because a large majority of projects do not use all of the files in a project directory (e.g. `Gulpfile.ts`, runtime vs tests) and parsing every file for types slows startup time. Instead, ts-node starts with the script file (e.g. `ts-node index.ts`) and TypeScript resolves dependencies based on imports and references.
989
990Occasionally, this optimization leads to missing types. Fortunately, there are other ways to include them in typechecking.
991
992For global definitions, you can use the `typeRoots` compiler option. This requires that your type definitions be structured as type packages (not loose TypeScript definition files). More details on how this works can be found in the [TypeScript Handbook](https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types).
993
994Example `tsconfig.json`:
995
996```jsonc
997{
998 "compilerOptions": {
999 "typeRoots" : ["./node_modules/@types", "./typings"]
1000 }
1001}
1002```
1003
1004Example project structure:
1005
1006```text
1007<project_root>/
1008-- tsconfig.json
1009-- typings/
1010 -- <module_name>/
1011 -- index.d.ts
1012```
1013
1014Example module declaration file:
1015
1016```typescript twoslash
1017declare module '<module_name>' {
1018 // module definitions go here
1019}
1020```
1021
1022For module definitions, you can use [`paths`](https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping):
1023
1024```jsonc title="tsconfig.json"
1025{
1026 "compilerOptions": {
1027 "baseUrl": ".",
1028 "paths": {
1029 "custom-module-type": ["types/custom-module-type"]
1030 }
1031 }
1032}
1033```
1034
1035Another option is [triple-slash directives](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). This may be helpful if you prefer not to change your `compilerOptions` or structure your type definitions for `typeRoots`. Below is an example of a triple-slash directive as a relative path within your project:
1036
1037```typescript twoslash
1038/// <reference path="./types/lib_greeter" />
1039import {Greeter} from "lib_greeter"
1040const g = new Greeter();
1041g.sayHello();
1042```
1043
1044If none of the above work, and you *must* use `files`, `include`, or `exclude`, enable our [`files`](#files) option.
1045
1046## npx, yarn dlx, and node_modules
1047
1048When executing TypeScript with `npx` or `yarn dlx`, the code resides within a temporary `node_modules` directory.
1049
1050The contents of `node_modules` are ignored by default. If execution fails, enable [`skipIgnore`](#skipignore).
1051
1052<!--See also: [npx and yarn dlx](./recipes/npx-and-yarn-dlx.md)-->
1053
1054# Performance
1055
1056These tricks will make ts-node faster.
1057
1058## Skip typechecking
1059
1060It is often better to typecheck as part of your tests or linting. You can run `tsc --noEmit` to do this. In these cases, ts-node can skip typechecking, making it much faster.
1061
1062To skip typechecking in ts-node, do one of the following:
1063
1064* Enable [swc](#swc)
1065 * This is by far the fastest option
1066* Enable [`transpileOnly`](#transpileonly) to skip typechecking without swc
1067
1068## With typechecking
1069
1070If you absolutely must typecheck in ts-node:
1071
1072* Avoid dynamic `require()` which may trigger repeated typechecking; prefer `import`
1073* Try with and without `--files`; one may be faster depending on your project
1074* Check `tsc --showConfig`; make sure all executed files are included
1075* Enable [`skipLibCheck`](https://www.typescriptlang.org/tsconfig#skipLibCheck)
1076* Set a [`types`](https://www.typescriptlang.org/tsconfig#types) array to avoid loading unnecessary `@types`
1077
1078# Advanced
1079
1080## How it works
1081
1082ts-node works by registering hooks for `.ts`, `.tsx`, `.js`, and/or `.jsx` extensions.
1083
1084Vanilla `node` loads `.js` by reading code from disk and executing it. Our hook runs in the middle, transforming code from TypeScript to JavaScript and passing the result to `node` for execution. This transformation will respect your `tsconfig.json` as if you had compiled via `tsc`.
1085
1086We also register a few other hooks to apply sourcemaps to stack traces and remap from `.js` imports to `.ts`.
1087
1088## Ignored files
1089
1090ts-node transforms certain files and ignores others. We refer to this mechanism as "scoping." There are various
1091options to configure scoping, so that ts-node transforms only the files in your project.
1092
1093> **Warning:**
1094>
1095> An ignored file can still be executed by node.js. Ignoring a file means we do not transform it from TypeScript into JavaScript, but it does not prevent execution.
1096>
1097> If a file requires transformation but is ignored, node may either fail to resolve it or attempt to execute it as vanilla JavaScript. This may cause syntax errors or other failures, because node does not understand TypeScript type syntax nor bleeding-edge ECMAScript features.
1098
1099### File extensions
1100
1101`.js` and `.jsx` are only transformed when [`allowJs`](https://www.typescriptlang.org/docs/handbook/compiler-options.html#compiler-options) is enabled.
1102
1103`.tsx` and `.jsx` are only transformed when [`jsx`](https://www.typescriptlang.org/docs/handbook/jsx.html) is enabled.
1104
1105> **Warning:**
1106>
1107> When ts-node is used with `allowJs`, *all* non-ignored JavaScript files are transformed by ts-node.
1108
1109### Skipping `node_modules`
1110
1111By default, ts-node avoids compiling files in `/node_modules/` for three reasons:
1112
11131. Modules should always be published in a format node.js can consume
11142. Transpiling the entire dependency tree will make your project slower
11153. Differing behaviours between TypeScript and node.js (e.g. ES2015 modules) can result in a project that works until you decide to support a feature natively from node.js
1116
1117If you need to import uncompiled TypeScript in `node_modules`, use [`--skipIgnore`](#skipignore) or [`TS_NODE_SKIP_IGNORE`](#skipignore) to bypass this restriction.
1118
1119### Skipping pre-compiled TypeScript
1120
1121If a compiled JavaScript file with the same name as a TypeScript file already exists, the TypeScript file will be ignored. ts-node will import the pre-compiled JavaScript.
1122
1123To force ts-node to import the TypeScript source, not the precompiled JavaScript, use [`--preferTsExts`](#prefertsexts).
1124
1125### Scope by directory
1126
1127Our [`scope`](#scope) and [`scopeDir`](#scopedir) options will limit transformation to files
1128within a directory.
1129
1130### Ignore by regexp
1131
1132Our [`ignore`](#ignore) option will ignore files matching one or more regular expressions.
1133
1134## paths and baseUrl&#xA;
1135
1136You can use ts-node together with [tsconfig-paths](https://www.npmjs.com/package/tsconfig-paths) to load modules according to the `paths` section in `tsconfig.json`.
1137
1138```jsonc title="tsconfig.json"
1139{
1140 "ts-node": {
1141 // Do not forget to `npm i -D tsconfig-paths`
1142 "require": ["tsconfig-paths/register"]
1143 }
1144}
1145```
1146
1147### Why is this not built-in to ts-node?
1148
1149The official TypeScript Handbook explains the intended purpose for `"paths"` in ["Additional module resolution flags"](https://www.typescriptlang.org/docs/handbook/module-resolution.html#additional-module-resolution-flags).
1150
1151> The TypeScript compiler has a set of additional flags to *inform* the compiler of transformations that are expected to happen to the sources to generate the final output.
1152>
1153> It is important to note that the compiler will not perform any of these transformations; it just uses these pieces of information to guide the process of resolving a module import to its definition file.
1154
1155This means `"paths"` are intended to describe mappings that the build tool or runtime *already* performs, not to tell the build tool or
1156runtime how to resolve modules. In other words, they intend us to write our imports in a way `node` already understands. For this reason, ts-node does not modify `node`'s module resolution behavior to implement `"paths"` mappings.
1157
1158## Third-party compilers
1159
1160Some projects require a patched typescript compiler which adds additional features. For example, [`ttypescript`](https://github.com/cevek/ttypescript/tree/master/packages/ttypescript) and [`ts-patch`](https://github.com/nonara/ts-patch#readme)
1161add the ability to configure custom transformers. These are drop-in replacements for the vanilla `typescript` module and
1162implement the same API.
1163
1164For example, to use `ttypescript` and `ts-transformer-keys`, add this to your `tsconfig.json`:
1165
1166```jsonc title="tsconfig.json"
1167{
1168 "ts-node": {
1169 // This can be omitted when using ts-patch
1170 "compiler": "ttypescript"
1171 },
1172 "compilerOptions": {
1173 // plugin configuration is the same for both ts-patch and ttypescript
1174 "plugins": [
1175 { "transform": "ts-transformer-keys/transformer" }
1176 ]
1177 }
1178}
1179```
1180
1181## Transpilers
1182
1183ts-node supports third-party transpilers as plugins. Transpilers such as swc can transform TypeScript into JavaScript
1184much faster than the TypeScript compiler. You will still benefit from ts-node's automatic `tsconfig.json` discovery,
1185sourcemap support, and global ts-node CLI. Plugins automatically derive an appropriate configuration from your existing
1186`tsconfig.json` which simplifies project boilerplate.
1187
1188> **What is the difference between a compiler and a transpiler?**
1189>
1190> For our purposes, a compiler implements TypeScript's API and can perform typechecking.
1191> A third-party transpiler does not. Both transform TypeScript into JavaScript.
1192
1193### Third-party plugins
1194
1195The `transpiler` option allows using third-party transpiler plugins with ts-node. `transpiler` must be given the
1196name of a module which can be `require()`d. The built-in `swc` plugin is exposed as `ts-node/transpilers/swc`.
1197
1198For example, to use a hypothetical "@cspotcode/fast-ts-compiler", first install it into your project: `npm install @cspotcode/fast-ts-compiler`
1199
1200Then add the following to your tsconfig:
1201
1202```jsonc title="tsconfig.json"
1203{
1204 "ts-node": {
1205 "transpileOnly": true,
1206 "transpiler": "@cspotcode/fast-ts-compiler"
1207 }
1208}
1209```
1210
1211### Write your own plugin
1212
1213To write your own transpiler plugin, check our [API docs](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html).
1214
1215Plugins are `require()`d by ts-node, so they can be a local script or a node module published to npm. The module must
1216export a `create` function described by our
1217[`TranspilerModule`](https://typestrong.org/ts-node/api/interfaces/TranspilerModule.html) interface. `create` is
1218invoked by ts-node at startup to create one or more transpiler instances. The instances are used to transform
1219TypeScript into JavaScript.
1220
1221For a working example, check out out our bundled swc plugin: https://github.com/TypeStrong/ts-node/blob/main/src/transpilers/swc.ts
1222
1223## Module type overrides
1224
1225> Wherever possible, it is recommended to use TypeScript's [`NodeNext` or `Node16` mode](https://www.typescriptlang.org/docs/handbook/esm-node.html) instead of the options described
1226> in this section. Setting `"module": "NodeNext"` and using the `.cts` file extension should work well for most projects.
1227
1228When deciding how a file should be compiled and executed -- as either CommonJS or native ECMAScript module -- ts-node matches
1229`node` and `tsc` behavior. This means TypeScript files are transformed according to your `tsconfig.json` `"module"`
1230option and executed according to node's rules for the `package.json` `"type"` field. Set `"module": "NodeNext"` and everything should work.
1231
1232In rare cases, you may need to override this behavior for some files. For example, some tools read a `name-of-tool.config.ts`
1233and require that file to execute as CommonJS. If you have `package.json` configured with `"type": "module"` and `tsconfig.json` with
1234`"module": "esnext"`, the config is native ECMAScript by default and will raise an error. You will need to force the config and
1235any supporting scripts to execute as CommonJS.
1236
1237In these situations, our `moduleTypes` option can override certain files to be
1238CommonJS or ESM. Similar overriding is possible by using `.mts`, `.cts`, `.cjs` and `.mjs` file extensions.
1239`moduleTypes` achieves the same effect for `.ts` and `.js` files, and *also* overrides your `tsconfig.json` `"module"`
1240config appropriately.
1241
1242The following example tells ts-node to execute a webpack config as CommonJS:
1243
1244```jsonc title="tsconfig.json"
1245{
1246 "ts-node": {
1247 "transpileOnly": true,
1248 "moduleTypes": {
1249 "webpack.config.ts": "cjs",
1250 // Globs are also supported with the same behavior as tsconfig "include"
1251 "webpack-config-scripts/**/*": "cjs"
1252 }
1253 },
1254 "compilerOptions": {
1255 "module": "es2020",
1256 "target": "es2020"
1257 }
1258}
1259```
1260
1261Each key is a glob pattern with the same syntax as tsconfig's `"include"` array.
1262When multiple patterns match the same file, the last pattern takes precedence.
1263
1264* `cjs` overrides matches files to compile and execute as CommonJS.
1265* `esm` overrides matches files to compile and execute as native ECMAScript modules.
1266* `package` resets either of the above to default behavior, which obeys `package.json` `"type"` and `tsconfig.json` `"module"` options.
1267
1268### Caveats
1269
1270Files with an overridden module type are transformed with the same limitations as [`isolatedModules`](https://www.typescriptlang.org/tsconfig#isolatedModules). This will only affect rare cases such as using `const enum`s with [`preserveConstEnums`](https://www.typescriptlang.org/tsconfig#preserveConstEnums) disabled.
1271
1272This feature is meant to facilitate scenarios where normal `compilerOptions` and `package.json` configuration is not possible. For example, a `webpack.config.ts` cannot be given its own `package.json` to override `"type"`. Wherever possible you should favor using traditional `package.json` and `tsconfig.json` configurations.
1273
1274## API
1275
1276ts-node's complete API is documented here: [API Docs](https://typestrong.org/ts-node/api/)
1277
1278Here are a few highlights of what you can accomplish:
1279
1280* [`create()`](https://typestrong.org/ts-node/api/index.html#create) creates ts-node's compiler service without
1281 registering any hooks.
1282* [`createRepl()`](https://typestrong.org/ts-node/api/index.html#createRepl) creates an instance of our REPL service, so
1283 you can create your own TypeScript-powered REPLs.
1284* [`createEsmHooks()`](https://typestrong.org/ts-node/api/index.html#createEsmHooks) creates our ESM loader hooks,
1285 suitable for composing with other loaders or augmenting with additional features.
1286
1287# Recipes
1288
1289## Watching and restarting
1290
1291ts-node focuses on adding first-class TypeScript support to node. Watching files and code reloads are out of scope for the project.
1292
1293If you want to restart the `ts-node` process on file change, existing node.js tools such as [nodemon](https://github.com/remy/nodemon), [onchange](https://github.com/Qard/onchange) and [node-dev](https://github.com/fgnass/node-dev) work.
1294
1295There's also [`ts-node-dev`](https://github.com/whitecolor/ts-node-dev), a modified version of [`node-dev`](https://github.com/fgnass/node-dev) using `ts-node` for compilation that will restart the process on file change. Note that `ts-node-dev` is incompatible with our native ESM loader.
1296
1297## AVA
1298
1299Assuming you are configuring AVA via your `package.json`, add one of the following configurations.
1300
1301### CommonJS
1302
1303Use this configuration if your `package.json` does not have `"type": "module"`.
1304
1305```jsonc title="package.json"
1306{
1307 "ava": {
1308 "extensions": [
1309 "ts"
1310 ],
1311 "require": [
1312 "ts-node/register"
1313 ]
1314 }
1315}
1316```
1317
1318### Native ECMAScript modules
1319
1320This configuration is necessary if your `package.json` has `"type": "module"`.
1321
1322```jsonc title="package.json"
1323{
1324 "ava": {
1325 "extensions": {
1326 "ts": "module"
1327 },
1328 "nonSemVerExperiments": {
1329 "configurableModuleFormat": true
1330 },
1331 "nodeArguments": [
1332 "--loader=ts-node/esm"
1333 ]
1334 }
1335}
1336```
1337
1338## Gulp
1339
1340ts-node support is built-in to gulp.
1341
1342```sh
1343# Create a `gulpfile.ts` and run `gulp`.
1344gulp
1345```
1346
1347See also: https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles#transpilation
1348
1349## IntelliJ and Webstorm
1350
1351Create a new Node.js configuration and add `-r ts-node/register` to "Node parameters."
1352
1353**Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in IntelliJ, specify under "Environment Variables": `TS_NODE_PROJECT=<tsconfig.json>`.
1354
1355## Mocha
1356
1357### Mocha 7 and newer
1358
1359```shell
1360mocha --require ts-node/register --extensions ts,tsx --watch --watch-files src 'tests/**/*.{ts,tsx}' [...args]
1361```
1362
1363Or specify options via your mocha config file.
1364
1365```jsonc title=".mocharc.json"
1366{
1367 // Specify "require" for CommonJS
1368 "require": "ts-node/register",
1369 // Specify "loader" for native ESM
1370 "loader": "ts-node/esm",
1371 "extensions": ["ts", "tsx"],
1372 "spec": [
1373 "tests/**/*.spec.*"
1374 ],
1375 "watch-files": [
1376 "src"
1377 ]
1378}
1379```
1380
1381See also: https://mochajs.org/#configuring-mocha-nodejs
1382
1383### Mocha <=6
1384
1385```shell
1386mocha --require ts-node/register --watch-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
1387```
1388
1389**Note:** `--watch-extensions` is only used in `--watch` mode.
1390
1391## Tape
1392
1393```shell
1394ts-node node_modules/tape/bin/tape [...args]
1395```
1396
1397## Visual Studio Code
1398
1399Create a new Node.js debug configuration, add `-r ts-node/register` to node args and move the `program` to the `args` list (so VS Code doesn't look for `outFiles`).
1400
1401```jsonc title=".vscode/launch.json"
1402{
1403 "configurations": [{
1404 "type": "node",
1405 "request": "launch",
1406 "name": "Launch Program",
1407 "runtimeArgs": [
1408 "-r",
1409 "ts-node/register"
1410 ],
1411 "args": [
1412 "${workspaceFolder}/src/index.ts"
1413 ]
1414 }],
1415}
1416```
1417
1418**Note:** If you are using the `--project <tsconfig.json>` command line argument as per the [Configuration Options](#configuration), and want to apply this same behavior when launching in VS Code, add an "env" key into the launch configuration: `"env": { "TS_NODE_PROJECT": "<tsconfig.json>" }`.
1419
1420## Other
1421
1422In many cases, setting [`NODE_OPTIONS`](https://nodejs.org/api/cli.html#cli_node_options_options) will enable `ts-node` within other node tools, child processes, and worker threads.
1423
1424```shell
1425NODE_OPTIONS="-r ts-node/register"
1426```
1427
1428Or, if you require native ESM support:
1429
1430```shell
1431NODE_OPTIONS="--loader ts-node/esm"
1432```
1433
1434This tells any node processes which receive this environment variable to install `ts-node`'s hooks before executing other code.
1435
1436# License
1437
1438ts-node is licensed under the MIT license. [MIT](https://github.com/TypeStrong/ts-node/blob/main/LICENSE)
1439
1440ts-node includes source code from Node.js which is licensed under the MIT license. [Node.js license information](https://raw.githubusercontent.com/nodejs/node/master/LICENSE)
1441
1442ts-node includes source code from the TypeScript compiler which is licensed under the Apache License 2.0. [TypeScript license information](https://github.com/microsoft/TypeScript/blob/master/LICENSE.txt)