Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

TypeScript execution and REPL for node.js

License

NotificationsYou must be signed in to change notification settings

TypeStrong/ts-node

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

TypeScript Node

NPM versionNPM downloadsBuild statusTest coverage

TypeScript execution and REPL for node.js, with source map and native ESM support.

The latest documentation can also be found on our website:https://typestrong.org/ts-node

Table of Contents

Overview

ts-node is a TypeScript execution engine and REPL for Node.js.

It JIT transforms TypeScript into JavaScript, enabling you to directly execute TypeScript on Node.js without precompiling.This is accomplished by hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.jstools and libraries.

Features

  • Automatic sourcemaps in stack traces
  • Automatictsconfig.json parsing
  • Automatic defaults to match your node version
  • Typechecking (optional)
  • REPL
  • Write standalone scripts
  • Native ESM loader
  • Use third-party transpilers
  • Use custom transformers
  • Integrate with test runners, debuggers, and CLI tools
  • Compatible with pre-compilation for production

TypeScript REPL

Installation

# Locally in your project.npm install -D typescriptnpm install -D ts-node# Or globally with TypeScript.npm install -g typescriptnpm install -g ts-node# Depending on configuration, you may also need thesenpm install -D tslib @types/node

Tip: Installing modules locally allows you to control and share the versions throughpackage.json. ts-node will always resolve the compiler fromcwd before checking relative to its own installation.

Usage

Command Line

# 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 --transpileOnlyts-node-transpile-only script.ts# Equivalent to ts-node --cwdModets-node-cwd script.ts# Equivalent to ts-node --esmts-node-esm script.ts

Shebang

To write scripts with maximum portability,specify options in yourtsconfig.json and omit them from the shebang.

#!/usr/bin/env ts-node// ts-node options are read from tsconfig.jsonconsole.log("Hello, world!")

Including options within the shebang requires theenv -S flag, which is available on recent versions ofenv. (compatibility)

#!/usr/bin/env -S ts-node --files// This shebang works on Mac and Linux with newer versions of env// Technically, Mac allows omitting `-S`, but Linux requires it

To test your version ofenv for compatibility with-S:

# Note that these unusual quotes are necessary/usr/bin/env --debug'-S echo foo bar'

node flags and other tools

You can register ts-node without using our CLI:node -r ts-node/register andnode --loader ts-node/esm

In many cases, settingNODE_OPTIONS will enablets-node within other node tools, child processes, and worker threads. This can be combined with other node flags.

NODE_OPTIONS="-r ts-node/register --no-warnings" node ./index.ts

Or, if you require native ESM support:

NODE_OPTIONS="--loader ts-node/esm"

This tells any node processes which receive this environment variable to installts-node's hooks before executing other code.

If you are invoking node directly, you can avoid the environment variable and pass those flags to node.

node --loader ts-node/esm --inspect ./index.ts

Programmatic

You can require ts-node and register the loader for future requires by usingrequire('ts-node').register({ /* options */ }).

Check out ourAPI for more features.

Configuration

ts-node supports a variety of options which can be specified viatsconfig.json, as CLI flags, as environment variables, or programmatically.

For a complete list, seeOptions.

CLI flags

ts-node CLI flags must comebefore the entrypoint script. For example:

$ ts-node --project tsconfig-dev.json say-hello.ts RonaldHello, Ronald!

Via tsconfig.json (recommended)

ts-node automatically finds and loadstsconfig.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 asnode --require ts-node/register and when using shebangs.

Use--skipProject to skip loading thetsconfig.json. Use--project to explicitly specify the path to atsconfig.json.

When searching, it is resolved usingthe same search behavior astsc. 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().

You can use this sample configuration as a starting point:

{// This is an alias to@tsconfig/node16: https://github.com/tsconfig/bases"extends":"ts-node/node16/tsconfig.json",// Most ts-node options can be specified here using their programmatic names."ts-node":{// It is faster to skip typechecking.// Remove if you want ts-node to do typechecking."transpileOnly":true,"files":true,"compilerOptions":{// compilerOptions specified here will override those declared below,// but *only* in ts-node.  Useful if you want ts-node and tsc to use// different options with a single tsconfig.json.}},"compilerOptions":{// typescript options here}}

Our bundledJSON schema lists all compatible options.

@tsconfig/bases

@tsconfig/bases maintains recommended configurations for several node versions.As a convenience, these are bundled with ts-node.

{"extends":"ts-node/node16/tsconfig.json",// Or install directly with `npm i -D @tsconfig/node16`"extends":"@tsconfig/node16/tsconfig.json",}

Default config

If notsconfig.json is loaded from disk, ts-node will use the newest recommended defaults from@tsconfig/bases compatible with yournode andtypescript versions.With the latestnode andtypescript, this is@tsconfig/node16.

Older versions oftypescript are incompatible with@tsconfig/node16. In those cases we will use an older default configuration.

When in doubt,ts-node --showConfig will log the configuration being used, andts-node -vv will lognode andtypescript versions.

node flags

node flags must be passed directly tonode; they cannot be passed to the ts-node binary nor can they be specified intsconfig.json

We recommend using theNODE_OPTIONS environment variable to pass options tonode.

NODE_OPTIONS='--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts

Alternatively, you can invokenode directly and install ts-node via--require/-r

node --trace-deprecation --abort-on-uncaught-exception -r ts-node/register ./index.ts

Options

All command-line flags support both--camelCase and--hyphen-case.

Most options can be declared in your tsconfig.json:Configuration via tsconfig.json

ts-node supports--print (-p),--eval (-e),--require (-r) and--interactive (-i) similar to thenode.js CLI.

ts-node supports--project and--showConfig similar to thetsc CLI.

Environment variables, where available, are inALL_CAPS

CLI Options

help

ts-node --help

Prints the help text

version

ts-node -vts-node -vvv

Prints the version.-vv includes node and typescript compiler versions.-vvv includes absolute paths to ts-node andtypescript installations.

eval

ts-node -e<typescript code># Examplets-node -e'console.log("Hello world!")'

Evaluate code

print

ts-node -p -e<typescript code># Examplets-node -p -e'"Hello world!"'

Print result of--eval

interactive

ts-node -i

Opens the REPL even if stdin does not appear to be a terminal

esm

ts-node --esmts-node-esm

Bootstrap with the ESM loader, enabling full ESM support

TSConfig Options

project

ts-node -P<path/to/tsconfig>ts-node --project<path/to/tsconfig>

Path to tsconfig file.

Note the uppercase-P. This is different fromtsc's-p/--project option.

Environment:TS_NODE_PROJECT

skipProject

ts-node --skipProject

Skip project config resolution and loading

Default:false
Environment:TS_NODE_SKIP_PROJECT

cwdMode

ts-node -cts-node --cwdModets-node-cwd

Resolve config relative to the current directory instead of the directory of the entrypoint script

compilerOptions

ts-node -O<json compilerOptions>ts-node --compilerOptions<json compilerOptions>

JSON object to merge with compiler options

Environment:TS_NODE_COMPILER_OPTIONS

showConfig

ts-node --showConfig

Print resolvedtsconfig.json, includingts-node options, and exit

Typechecking

transpileOnly

ts-node -Tts-node --transpileOnly

Use TypeScript's fastertranspileModule

Default:false
Environment:TS_NODE_TRANSPILE_ONLY

typeCheck

ts-node --typeCheck

Opposite of--transpileOnly

Default:true
Environment:TS_NODE_TYPE_CHECK

compilerHost

ts-node -Hts-node --compilerHost

Use TypeScript's compiler host API

Default:false
Environment:TS_NODE_COMPILER_HOST

files

ts-node --files

Loadfiles,include andexclude fromtsconfig.json on startup. This mayavoid certain typechecking failures. SeeMissing types for details.

Default:false
Environment:TS_NODE_FILES

ignoreDiagnostics

ts-node -D<code,code>ts-node --ignoreDiagnostics<code,code>

Ignore TypeScript warnings by diagnostic code

Environment:TS_NODE_IGNORE_DIAGNOSTICS

Transpilation Options

ignore

ts-node -I<regexp matching ignored files>ts-node --ignore<regexp matching ignored files>

Override the path patterns to skip compilation

Default:/node_modules/
Environment:TS_NODE_IGNORE

skipIgnore

ts-node --skipIgnore

Skip ignore checks

Default:false
Environment:TS_NODE_SKIP_IGNORE

compiler

ts-node -C<name>ts-node --compiler<name>

Specify a custom TypeScript compiler

Default:typescript
Environment:TS_NODE_COMPILER

swc

ts-node --swc

Transpile withswc. Implies--transpileOnly

Default:false

transpiler

ts-node --transpiler<name># Examplets-node --transpiler ts-node/transpilers/swc

Use a third-party, non-typechecking transpiler

preferTsExts

ts-node --preferTsExts

Re-order file extensions so that TypeScript imports are preferred

Default:false
Environment:TS_NODE_PREFER_TS_EXTS

Diagnostic Options

logError

ts-node --logError

Logs TypeScript errors to stderr instead of throwing exceptions

Default:false
Environment:TS_NODE_LOG_ERROR

pretty

ts-node --pretty

Use pretty diagnostic formatter

Default:false
Environment:TS_NODE_PRETTY

TS_NODE_DEBUG

TS_NODE_DEBUG=true ts-node

Enable debug logging

Advanced Options

require

ts-node -r<module name or path>ts-node --require<module name or path>

Require a node module before execution

cwd

ts-node --cwd<path/to/directory>

Behave as if invoked in this working directory

Default:process.cwd()
Environment:TS_NODE_CWD

emit

ts-node --emit

Emit output files into.ts-node directory. Requires--compilerHost

Default:false
Environment:TS_NODE_EMIT

scope

ts-node --scope

Scope compiler to files withinscopeDir. Anything outside this directory is ignored.

Default:false
Environment:TS_NODE_SCOPE

scopeDir

ts-node --scopeDir<path/to/directory>

Directory within which compiler is limited whenscope is enabled.

Default: First of:tsconfig.json "rootDir" if specified, directory containingtsconfig.json, or cwd if notsconfig.json is loaded.
Environment:TS_NODE_SCOPE_DIR

moduleTypes

Override the module type of certain files, ignoring thepackage.json"type" field. SeeModule type overrides for details.

Default: obeyspackage.json"type" andtsconfig.json"module"
Can only be specified viatsconfig.json or API.

TS_NODE_HISTORY

TS_NODE_HISTORY=<path/to/history/file> ts-node

Path to history file for REPL

Default:~/.ts_node_repl_history

noExperimentalReplAwait

ts-node --noExperimentalReplAwait

Disable top-level await in REPL. Equivalent to node's--no-experimental-repl-await

Default: Enabled if TypeScript version is 3.8 or higher and target is ES2018 or higher.
Environment:TS_NODE_EXPERIMENTAL_REPL_AWAIT setfalse to disable

experimentalResolver

Enable experimental hooks that re-map imports and require calls to support:

  • remapping extensions, e.g. so thatimport "./foo.js" will executefoo.ts. Currently the following extensions will be mapped:
    • .js to.ts,.tsx, or.jsx
    • .cjs to.cts
    • .mjs to.mts
    • .jsx to.tsx
  • including file extensions in CommonJS, for consistency with ESM where this is often mandatory

In the future, this hook will also support:

  • baseUrl,paths
  • rootDirs
  • outDir torootDir mappings for composite projects and monorepos

For details, see#1514.

Default:false, but will likely be enabled by default in a future version
Can only be specified viatsconfig.json or API.

experimentalSpecifierResolution

ts-node --experimentalSpecifierResolution node

Like node's--experimental-specifier-resolution, but can also be set in yourtsconfig.json for convenience.Requiresesm to be enabled.

Default:explicit

API Options

The API includesadditional options not shown here.

SWC

SWC support is built-in via the--swc flag or"swc": true tsconfig option.

SWC is a TypeScript-compatible transpiler implemented in Rust. This makes it an order of magnitude faster than vanillatranspileOnly.

To use it, first install@swc/core or@swc/wasm. If usingimportHelpers, also install@swc/helpers. Iftarget is less than "es2015" and usingasync/await or generator functions, also installregenerator-runtime.

npm i -D @swc/core @swc/helpers regenerator-runtime

Then add the following to yourtsconfig.json.

{"ts-node":{"swc":true}}

SWC uses@swc/helpers instead oftslib. If you have enabledimportHelpers, you must also install@swc/helpers.

CommonJS vs native ECMAScript modules

TypeScript is almost always written using modernimport 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 nativeimport syntax, using node's native ESM support. Configuration is different for each.

Here is a brief comparison of the two.

CommonJSNative ECMAScript modules
Write nativeimport syntaxWrite nativeimport syntax
Transformsimport intorequire()Does not transformimport
Node executes scripts using the classicCommonJS loaderNode executes scripts using the newESM loader
Use any of:
ts-node
node -r ts-node/register
NODE_OPTIONS="ts-node/register" node
require('ts-node').register({/* options */})
Use any of:
ts-node --esm
ts-node-esm
Set"esm": true intsconfig.json
node --loader ts-node/esm
NODE_OPTIONS="--loader ts-node/esm" node

CommonJS

Transforming to CommonJS is typically simpler and more widely supported because it is older. You must remove"type": "module" frompackage.json and set"module": "CommonJS" intsconfig.json.

{// This can be omitted; commonjs is the default"type":"commonjs"}
{"compilerOptions":{"module":"CommonJS"}}

If you must keep"module": "ESNext" fortsc, webpack, or another build tool, you can set an override for ts-node.

{"compilerOptions":{"module":"ESNext"},"ts-node":{"compilerOptions":{"module":"CommonJS"}}}

Native ECMAScript modules

Node's ESM loader hooks areexperimental and subject to change. ts-node's ESM support is as stable as possible, but it relies on APIs which node canand will break in new versions of node. Thus it is not recommended for production.

For complete usage, limitations, and to provide feedback, see#1007.

You must set"type": "module" inpackage.json and"module": "ESNext" intsconfig.json.

{"type":"module"}
{"compilerOptions":{"module":"ESNext"// or ES2015, ES2020},"ts-node":{// Tell ts-node CLI to install the --loader automatically, explained below"esm":true}}

You must also ensure node is passed--loader. The ts-node CLI will do this automatically with ouresm option.

Note:--esm must spawn a child process to pass it--loader. This may change if node adds the ability to install loader hooksinto the current process.

# pass the flagts-node --esm# Use the convenience binaryts-node-esm# or add `"esm": true` to your tsconfig.json to make it automaticts-node

If you are not using our CLI, pass the loader flag to node.

node --loader ts-node/esm ./index.ts# Or via environment variableNODE_OPTIONS="--loader ts-node/esm" node ./index.ts

Troubleshooting

Configuration

ts-node uses sensible default configurations to reduce boilerplate while still respectingtsconfig.json if youhave one. If you are unsure which configuration is used, you can log it withts-node --showConfig. This is similar totsc --showConfig but includes"ts-node" options as well.

ts-node also respects your locally-installedtypescript version, but global installations fallback to the globally-installedtypescript. If you are unsure which versions are used,ts-node -vv will log them.

$ ts-node -vvts-node v10.0.0node v16.1.0compiler v4.2.2$ ts-node --showConfig{"compilerOptions": {"target":"es6","lib": ["es6","dom"    ],"rootDir":"./src","outDir":"./.ts-node","module":"commonjs","moduleResolution":"node","strict": true,"declaration": false,"sourceMap": true,"inlineSources": true,"types": ["node"    ],"stripInternal": true,"incremental": true,"skipLibCheck": true,"importsNotUsedAsValues":"error","inlineSourceMap": false,"noEmit":false  },"ts-node": {"cwd":"/d/project","projectSearchDir":"/d/project","require": [],"project":"/d/project/tsconfig.json"  }}

Common errors

It is important to differentiate between errors from ts-node, errors from the TypeScript compiler, and errors fromnode. 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.

TSError

Type errors from the compiler are thrown as aTSError. These are the same as errors you get fromtsc.

SyntaxError

Any error that is not aTSError is from node.js (e.g.SyntaxError), and cannot be fixed by TypeScript or ts-node. These are bugs in your code or configuration.

Unsupported JavaScript syntax

Your version ofnode may not support all JavaScript syntax supported by TypeScript. The compiler must transform this syntax via "downleveling," which is controlled bythetsconfig"target" option. Otherwise your code will compile fine, but node will throw aSyntaxError.

For example,node 12 does not understand the?. optional chaining operator. If you use"target": "esnext", then the following TypeScript syntax:

constbar:string|undefined=foo?.bar;

will compile into this #"auto" data-snippet-clipboard-copy-content="const a = foo?.bar;">

consta=foo?.bar;

When you try to run this code, node 12 will throw aSyntaxError. To fix this, you must switch to"target": "es2019" or lower so TypeScript transforms?. into somethingnode can understand.

ERR_REQUIRE_ESM

This error is thrown by node when a module isrequire()d, but node believes it should execute as native ESM. This can happen for a few reasons:

  • You have installed an ESM dependency but your own code compiles to CommonJS.
    • Solution: configure your project to compile and execute as native ESM.Docs
    • Solution: downgrade the dependency to an older, CommonJS version.
  • You have moved your project to ESM but still have a config file, such aswebpack.config.ts, which must be executed as CommonJS
    • Solution: if supported by the relevant tool, rename your config file to.cts
    • Solution: Configure a module type override.Docs
  • You have a mix of CommonJS and native ESM in your project
    • Solution: double-check all package.json "type" and tsconfig.json "module" configurationDocs
    • Solution: consider simplifying by making your project entirely CommonJS or entirely native ESM

ERR_UNKNOWN_FILE_EXTENSION

This 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:

  • You are using a tool which has an extensionless binary, such asmocha.
    • CommonJS supports extensionless files but native ESM does not.
    • Solution: upgrade to ts-node >=v10.6.0, which implements a workaround.
  • Our ESM loader is not installed.
    • Solution: Usets-node-esm,ts-node --esm, or add"ts-node": {"esm": true} to your tsconfig.json.Docs
  • You have moved your project to ESM but still have a config file, such aswebpack.config.ts, which must be executed as CommonJS
    • Solution: if supported by the relevant tool, rename your config file to.cts
    • Solution: Configure a module type override.Docs

Missing Types

ts-node doesnot eagerly loadfiles,include orexclude 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.

Occasionally, this optimization leads to missing types. Fortunately, there are other ways to include them in typechecking.

For global definitions, you can use thetypeRoots 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 theTypeScript Handbook.

Exampletsconfig.json:

{"compilerOptions":{"typeRoots" :["./node_modules/@types","./typings"]}}

Example project structure:

<project_root>/-- tsconfig.json-- typings/  -- <module_name>/    -- index.d.ts

Example module declaration file:

declare module'<module_name>'{// module definitions go here}

For module definitions, you can usepaths:

{"compilerOptions":{"baseUrl":".","paths":{"custom-module-type":["types/custom-module-type"]}}}

Another option istriple-slash directives. This may be helpful if you prefer not to change yourcompilerOptions or structure your type definitions fortypeRoots. Below is an example of a triple-slash directive as a relative path within your project:

/// <reference path="./types/lib_greeter" />import{Greeter}from"lib_greeter"constg=newGreeter();g.sayHello();

If none of the above work, and youmust usefiles,include, orexclude, enable ourfiles option.

npx, yarn dlx, and node_modules

When executing TypeScript withnpx oryarn dlx, the code resides within a temporarynode_modules directory.

The contents ofnode_modules are ignored by default. If execution fails, enableskipIgnore.

Performance

These tricks will make ts-node faster.

Skip typechecking

It is often better to typecheck as part of your tests or linting. You can runtsc --noEmit to do this. In these cases, ts-node can skip typechecking, making it much faster.

To skip typechecking in ts-node, do one of the following:

  • Enableswc
    • This is by far the fastest option
  • EnabletranspileOnly to skip typechecking without swc

With typechecking

If you absolutely must typecheck in ts-node:

  • Avoid dynamicrequire() which may trigger repeated typechecking; preferimport
  • Try with and without--files; one may be faster depending on your project
  • Checktsc --showConfig; make sure all executed files are included
  • EnableskipLibCheck
  • Set atypes array to avoid loading unnecessary@types

Advanced

How it works

ts-node works by registering hooks for.ts,.tsx,.js, and/or.jsx extensions.

Vanillanode 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 tonode for execution. This transformation will respect yourtsconfig.json as if you had compiled viatsc.

We also register a few other hooks to apply sourcemaps to stack traces and remap from.js imports to.ts.

Ignored files

ts-node transforms certain files and ignores others. We refer to this mechanism as "scoping." There are variousoptions to configure scoping, so that ts-node transforms only the files in your project.

Warning:

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.

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.

File extensions

.js and.jsx are only transformed whenallowJs is enabled.

.tsx and.jsx are only transformed whenjsx is enabled.

Warning:

When ts-node is used withallowJs,all non-ignored JavaScript files are transformed by ts-node.

Skippingnode_modules

By default, ts-node avoids compiling files in/node_modules/ for three reasons:

  1. Modules should always be published in a format node.js can consume
  2. Transpiling the entire dependency tree will make your project slower
  3. 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

If you need to import uncompiled TypeScript innode_modules, use--skipIgnore orTS_NODE_SKIP_IGNORE to bypass this restriction.

Skipping pre-compiled TypeScript

If 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.

To force ts-node to import the TypeScript source, not the precompiled JavaScript, use--preferTsExts.

Scope by directory

Ourscope andscopeDir options will limit transformation to fileswithin a directory.

Ignore by regexp

Ourignore option will ignore files matching one or more regular expressions.

paths and baseUrl

You can use ts-node together withtsconfig-paths to load modules according to thepaths section intsconfig.json.

{"ts-node":{// Do not forget to `npm i -D tsconfig-paths`"require":["tsconfig-paths/register"]}}

Why is this not built-in to ts-node?

The official TypeScript Handbook explains the intended purpose for"paths" in"Additional module resolution flags".

The TypeScript compiler has a set of additional flags toinform the compiler of transformations that are expected to happen to the sources to generate the final output.

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.

This means"paths" are intended to describe mappings that the build tool or runtimealready performs, not to tell the build tool orruntime how to resolve modules. In other words, they intend us to write our imports in a waynode already understands. For this reason, ts-node does not modifynode's module resolution behavior to implement"paths" mappings.

Third-party compilers

Some projects require a patched typescript compiler which adds additional features. For example,ttypescript andts-patchadd the ability to configure custom transformers. These are drop-in replacements for the vanillatypescript module andimplement the same API.

For example, to usettypescript andts-transformer-keys, add this to yourtsconfig.json:

{"ts-node":{// This can be omitted when using ts-patch"compiler":"ttypescript"},"compilerOptions":{// plugin configuration is the same for both ts-patch and ttypescript"plugins":[{"transform":"ts-transformer-keys/transformer"}]}}

Transpilers

ts-node supports third-party transpilers as plugins. Transpilers such as swc can transform TypeScript into JavaScriptmuch faster than the TypeScript compiler. You will still benefit from ts-node's automatictsconfig.json discovery,sourcemap support, and global ts-node CLI. Plugins automatically derive an appropriate configuration from your existingtsconfig.json which simplifies project boilerplate.

What is the difference between a compiler and a transpiler?

For our purposes, a compiler implements TypeScript's API and can perform typechecking.A third-party transpiler does not. Both transform TypeScript into JavaScript.

Third-party plugins

Thetranspiler option allows using third-party transpiler plugins with ts-node.transpiler must be given thename of a module which can berequire()d. The built-inswc plugin is exposed asts-node/transpilers/swc.

For example, to use a hypothetical "@cspotcode/fast-ts-compiler", first install it into your project:npm install @cspotcode/fast-ts-compiler

Then add the following to your tsconfig:

{"ts-node":{"transpileOnly":true,"transpiler":"@cspotcode/fast-ts-compiler"}}

Write your own plugin

To write your own transpiler plugin, check ourAPI docs.

Plugins arerequire()d by ts-node, so they can be a local script or a node module published to npm. The module mustexport acreate function described by ourTranspilerModule interface.create isinvoked by ts-node at startup to create one or more transpiler instances. The instances are used to transformTypeScript into JavaScript.

For a working example, check out out our bundled swc plugin:https://github.com/TypeStrong/ts-node/blob/main/src/transpilers/swc.ts

Module type overrides

Wherever possible, it is recommended to use TypeScript'sNodeNext orNode16 mode instead of the options describedin this section. Setting"module": "NodeNext" and using the.cts file extension should work well for most projects.

When deciding how a file should be compiled and executed -- as either CommonJS or native ECMAScript module -- ts-node matchesnode andtsc behavior. This means TypeScript files are transformed according to yourtsconfig.json"module"option and executed according to node's rules for thepackage.json"type" field. Set"module": "NodeNext" and everything should work.

In rare cases, you may need to override this behavior for some files. For example, some tools read aname-of-tool.config.tsand require that file to execute as CommonJS. If you havepackage.json configured with"type": "module" andtsconfig.json with"module": "esnext", the config is native ECMAScript by default and will raise an error. You will need to force the config andany supporting scripts to execute as CommonJS.

In these situations, ourmoduleTypes option can override certain files to beCommonJS or ESM. Similar overriding is possible by using.mts,.cts,.cjs and.mjs file extensions.moduleTypes achieves the same effect for.ts and.js files, andalso overrides yourtsconfig.json"module"config appropriately.

The following example tells ts-node to execute a webpack config as CommonJS:

{"ts-node":{"transpileOnly":true,"moduleTypes":{"webpack.config.ts":"cjs",// Globs are also supported with the same behavior as tsconfig "include""webpack-config-scripts/**/*":"cjs"}},"compilerOptions":{"module":"es2020","target":"es2020"}}

Each key is a glob pattern with the same syntax as tsconfig's"include" array.When multiple patterns match the same file, the last pattern takes precedence.

  • cjs overrides matches files to compile and execute as CommonJS.
  • esm overrides matches files to compile and execute as native ECMAScript modules.
  • package resets either of the above to default behavior, which obeyspackage.json"type" andtsconfig.json"module" options.

Caveats

Files with an overridden module type are transformed with the same limitations asisolatedModules. This will only affect rare cases such as usingconst enums withpreserveConstEnums disabled.

This feature is meant to facilitate scenarios where normalcompilerOptions andpackage.json configuration is not possible. For example, awebpack.config.ts cannot be given its ownpackage.json to override"type". Wherever possible you should favor using traditionalpackage.json andtsconfig.json configurations.

API

ts-node's complete API is documented here:API Docs

Here are a few highlights of what you can accomplish:

  • create() creates ts-node's compiler service withoutregistering any hooks.
  • createRepl() creates an instance of our REPL service, soyou can create your own TypeScript-powered REPLs.
  • createEsmHooks() creates our ESM loader hooks,suitable for composing with other loaders or augmenting with additional features.

Recipes

Watching and restarting

ts-node focuses on adding first-class TypeScript support to node. Watching files and code reloads are out of scope for the project.

If you want to restart thets-node process on file change, existing node.js tools such asnodemon,onchange andnode-dev work.

There's alsots-node-dev, a modified version ofnode-dev usingts-node for compilation that will restart the process on file change. Note thatts-node-dev is incompatible with our native ESM loader.

AVA

Assuming you are configuring AVA via yourpackage.json, add one of the following configurations.

CommonJS

Use this configuration if yourpackage.json does not have"type": "module".

{"ava":{"extensions":["ts"],"require":["ts-node/register"]}}

Native ECMAScript modules

This configuration is necessary if yourpackage.json has"type": "module".

{"ava":{"extensions":{"ts":"module"},"nonSemVerExperiments":{"configurableModuleFormat":true},"nodeArguments":["--loader=ts-node/esm"]}}

Gulp

ts-node support is built-in to gulp.

# Create a `gulpfile.ts` and run `gulp`.gulp

See also:https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles#transpilation

IntelliJ and Webstorm

Create a new Node.js configuration and add-r ts-node/register to "Node parameters."

Note: If you are using the--project <tsconfig.json> command line argument as per theConfiguration Options, and want to apply this same behavior when launching in IntelliJ, specify under "Environment Variables":TS_NODE_PROJECT=<tsconfig.json>.

Mocha

Mocha 7 and newer

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

Or specify options via your mocha config file.

{// Specify "require" for CommonJS"require":"ts-node/register",// Specify "loader" for native ESM"loader":"ts-node/esm","extensions":["ts","tsx"],"spec":["tests/**/*.spec.*"],"watch-files":["src"]}

See also:https://mochajs.org/#configuring-mocha-nodejs

Mocha <=6

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

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

Tape

ts-node node_modules/tape/bin/tape [...args]

Visual Studio Code

Create a new Node.js debug configuration, add-r ts-node/register to node args and move theprogram to theargs list (so VS Code doesn't look foroutFiles).

{"configurations":[{"type":"node","request":"launch","name":"Launch Program","runtimeArgs":["-r","ts-node/register"],"args":["${workspaceFolder}/src/index.ts"]}],}

Note: If you are using the--project <tsconfig.json> command line argument as per theConfiguration Options, 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>" }.

Other

In many cases, settingNODE_OPTIONS will enablets-node within other node tools, child processes, and worker threads.

NODE_OPTIONS="-r ts-node/register"

Or, if you require native ESM support:

NODE_OPTIONS="--loader ts-node/esm"

This tells any node processes which receive this environment variable to installts-node's hooks before executing other code.

License

ts-node is licensed under the MIT license.MIT

ts-node includes source code from Node.js which is licensed under the MIT license.Node.js license information

ts-node includes source code from the TypeScript compiler which is licensed under the Apache License 2.0.TypeScript license information


[8]ページ先頭

©2009-2025 Movatter.jp