How To Change Order Of Ts Ranks
TypeScript execution and REPL for node.js, with source map and native ESM back up.
The latest documentation can as well be found on our website: https://typestrong.org/ts-node
Table of Contents
- Overview
- Features
- Installation
- Usage
- Shell
- Shebang
- Programmatic
- Developers
- Configuration
- CLI flags
- Via tsconfig.json (recommended)
- @tsconfig/bases
- Default config
-
node
flags
- Options
- Vanquish
- TSConfig
- Typechecking
- Transpilation
- Diagnostics
- Avant-garde
- API
- CommonJS vs native ECMAScript modules
- CommonJS
- Native ECMAScript modules
- Troubleshooting
- Agreement configuration
- Understanding Errors
-
TSError
-
SyntaxError
- Unsupported JavaScript syntax
-
- Make it fast
- Skip typechecking
- With typechecking
- Advanced
- How It Works
- Skipping
node_modules
- Skipping pre-compiled TypeScript
- Skipping
- paths and baseUrl
- Why is this not built-in to ts-node?
- Aid! My Types Are Missing!
- Third-political party compilers
- Transpilers
- swc
- Tertiary-party transpilers
- Writing your own integration
- Module blazon overrides
- Caveats
- How It Works
- Recipes
- Watching and Restarting
- AVA
- CommonJS
- Native ECMAScript modules
- Gulp
- IntelliJ and Webstorm
- Mocha
- Mocha seven and newer
- Mocha <=vi
- Record
- Visual Studio Code
- Other
- License
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 past hooking node's module loading APIs, enabling it to be used seamlessly alongside other Node.js tools and libraries.
Features
- Automated sourcemaps in stack traces
- Automatic
tsconfig.json
parsing - Automatic defaults to lucifer your node version
- Typechecking (optional)
- REPL
- Write standalone scripts
- Native ESM loader
- Use third-political party transpilers
- Apply custom transformers
- Integrate with test runners, debuggers, and CLI tools
- Compatible with pre-compilation for production
Installation
# Locally in your project. npm install -D typescript npm install -D ts-node # Or globally with TypeScript. npm install -yard typescript npm install -k ts-node # Depending on configuration, you may also need these npm install -D tslib @types/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
Beat out
# Execute a script as `node` + `tsc`. ts-node script.ts # Starts a TypeScript REPL. ts-node # Execute lawmaking with TypeScript. ts-node -e 'console.log("Hello, world!")' # Execute, and print, code with TypeScript. ts-node -p -e '"Hello, world!"' # Piping scripts to execute with TypeScript. echo 'console.log("Hello, world!")' | ts-node # Equivalent to ts-node --transpileOnly ts-node-transpile-but script.ts # Equivalent to ts-node --cwdMode ts-node-cwd script.ts # Equivalent to ts-node --esm ts-node-esm script.ts
Shebang
#!/usr/bin/env ts-node console . log ( "Hello, world!" )
Passing options via shebang requires the env -S
flag, which is available on recent versions of env
. (compatibility)
#!/usr/bin/env -Due south ts-node --files // This shebang works on Mac and Linux with newer versions of env // Technically, Mac allows omitting `-Southward`, but Linux requires it
To write scripts with maximum portability, specify all options in your tsconfig.json
and omit them from the shebang.
#!/usr/bin/env ts-node // This shebang works everywhere
To test your version of env
for compatibility:
# Note that these unusual quotes are necessary /usr/bin/env --debug '-South echo foo bar'
Programmatic
You can crave ts-node and register the loader for time to come requires past using require('ts-node').annals({ /* options */ })
. You tin besides employ file shortcuts - node -r ts-node/register
or node -r ts-node/register/transpile-only
- depending on your preferences.
Note: If y'all need to utilise advanced node.js CLI arguments (east.g. --inspect
), use them with node -r ts-node/register
instead of ts-node'southward 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 information technology uses the same code equally register
.
Configuration
ts-node supports a multifariousness of options which can exist specified via tsconfig.json
, as CLI flags, as surround variables, or programmatically.
For a consummate list, come across Options.
CLI flags
ts-node CLI flags must come before the entrypoint script. For example:
$ ts-node --project tsconfig-dev.json say-howdy.ts Ronald Hello, Ronald!
Via tsconfig.json (recommended)
ts-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 every bit node --require ts-node/register
and when using shebangs.
Use --skipProject
to skip loading the tsconfig.json
. Use --project
to explicitly specify the path to a tsconfig.json
.
When searching, information technology is resolved using the same search behavior as tsc
. Past 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 lot can use this sample configuration as a starting point:
{ // This is an alias to @tsconfig/node12: https://github.com/tsconfig/bases "extends": "ts-node/node12/tsconfig.json" , // Most ts-node options can be specified hither using their programmatic names. "ts-node": { // It is faster to skip typechecking. // Remove if you desire ts-node to do typechecking. "transpileOnly": truthful , "files": truthful , "compilerOptions": { // compilerOptions specified here volition override those declared below, // but *only* in ts-node. Useful if you lot desire ts-node and tsc to use // dissimilar options with a single tsconfig.json. } } , "compilerOptions": { // typescript options here } }
Our bundled JSON schema lists all uniform 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 no tsconfig.json
is loaded from disk, ts-node will employ the newest recommended defaults from @tsconfig/bases compatible with your node
and typescript
versions. With the latest node
and typescript
, this is @tsconfig/node16
.
Older versions of typescript
are incompatible with @tsconfig/node16
. In those cases we volition apply an older default configuration.
When in uncertainty, ts-node --showConfig
will log the configuration being used, and ts-node -vv
will log node
and typescript
versions.
node
flags
node
flags must exist passed directly to node
; they cannot be passed to the ts-node binary nor can they be specified in tsconfig.json
Nosotros recommend using the NODE_OPTIONS
environment variable to laissez passer options to node
.
NODE_OPTIONS= '--trace-deprecation --abort-on-uncaught-exception' ts-node ./index.ts
Alternatively, you can invoke node
direct and install ts-node via --crave
/-r
node --trace-deprecation --arrest-on-uncaught-exception -r ts-node/register ./alphabetize.ts
Options
ts-node
supports --print
(-p
), --eval
(-e
), --require
(-r
) and --interactive
(-i
) similar to the node.js CLI options.
All command-line flags support both --camelCase
and --hyphen-case
.
Surroundings variables, where available, are in ALL_CAPS
Shell
-
-h, --help
Prints the aid text -
-v, --version
Prints the version.-vv
prints node and typescript compiler versions, too -
-e, --eval
Evaluate code -
-p, --impress
Impress issue of--eval
-
-i, --interactive
Opens the REPL even if stdin does not announced to exist a terminal -
--esm
Bootstrap with the ESM loader, enabling full ESM support
TSConfig
-
-P, --project [path]
Path to TypeScript JSON project file
Environment:TS_NODE_PROJECT
-
--skipProject
Skip project config resolution and loading
Default:false
Environment:TS_NODE_SKIP_PROJECT
-
-c, --cwdMode
Resolve config relative to the current directory instead of the directory of the entrypoint script -
-O, --compilerOptions [opts]
JSON object to merge with compiler options
Surroundings:TS_NODE_COMPILER_OPTIONS
-
--showConfig
Print resolvedtsconfig.json
, includingts-node
options, and exit
Typechecking
-
-T, --transpileOnly
Employ TypeScript's fastertranspileModule
Default:false
Environment:TS_NODE_TRANSPILE_ONLY
-
--typeCheck
Opposite of--transpileOnly
Default:truthful
Environment:TS_NODE_TYPE_CHECK
-
-H, --compilerHost
Apply TypeScript's compiler host API
Default:false
Environment:TS_NODE_COMPILER_HOST
-
--files
Loadfiles
,include
andexclude
fromtsconfig.json
on startup
Default:false
Environment:TS_NODE_FILES
-
-D, --ignoreDiagnostics [lawmaking]
Ignore TypeScript warnings by diagnostic code
Environs:TS_NODE_IGNORE_DIAGNOSTICS
Transpilation
-
-I, --ignore [pattern]
Override the path patterns to skip compilation
Default:/node_modules/
Surroundings:TS_NODE_IGNORE
-
--skipIgnore
Skip ignore checks
Default:false
Environment:TS_NODE_SKIP_IGNORE
-
-C, --compiler [name]
Specify a custom TypeScript compiler
Default:typescript
Environment:TS_NODE_COMPILER
-
--swc
Transpile with swc. Implies--transpileOnly
Default:faux
-
--transpiler [name]
Specify a third-party, non-typechecking transpiler -
--preferTsExts
Re-order file extensions and then that TypeScript imports are preferred
Default:false
Environment:TS_NODE_PREFER_TS_EXTS
Diagnostics
-
--logError
Logs TypeScript errors to stderr instead of throwing exceptions
Default:false
Environment:TS_NODE_LOG_ERROR
-
--pretty
Use pretty diagnostic formatter
Default:imitation
Surround:TS_NODE_PRETTY
-
TS_NODE_DEBUG
Enable debug logging
Avant-garde
-
-r, --require [path]
Crave a node module earlier execution -
--cwd
Behave as if invoked in this working directory
Default:procedure.cwd()
Surroundings:TS_NODE_CWD
-
--emit
Emit output files into.ts-node
directory
Default:simulated
Environment:TS_NODE_EMIT
-
--scope
Telescopic compiler to files withinscopeDir
. Annihilation outside this directory is ignored.
*Default:false
Environment:TS_NODE_SCOPE
-
--scopeDir
Directory within which compiler is limited whentelescopic
is enabled.
Default: Beginning of:tsconfig.json
"rootDir" if specified, directory containingtsconfig.json
, or cwd if notsconfig.json
is loaded.
Surroundings:TS_NODE_SCOPE_DIR
-
moduleTypes
Override the module blazon of sure files, ignoring thepacket.json
"blazon"
field. Encounter Module blazon overrides for details.
Default: obeyspackage.json
"blazon"
andtsconfig.json
"module"
Tin just be specified viatsconfig.json
or API. -
TS_NODE_HISTORY
Path to history file for REPL
Default:~/.ts_node_repl_history
-
--noExperimentalReplAwait
Disable top-level await in REPL. Equivalent to node's--no-experimental-repl-expect
Default: Enabled if TypeScript version is iii.8 or higher and target is ES2018 or higher.
Environment:TS_NODE_EXPERIMENTAL_REPL_AWAIT
preparefalse
to disable -
experimentalResolverFeatures
Enable experimental features that re-map imports and require calls to support:baseUrl
,paths
,rootDirs
,.js
to.ts
file extension mappings,outDir
torootDir
mappings for composite projects and monorepos. For details, see #1514
Default:faux
Can only be specified viatsconfig.json
or API.
API
The API includes boosted options not shown here.
CommonJS vs native ECMAScript modules
TypeScript is nearly always written using modern import
syntax, but it is also transformed before existence executed by the underlying runtime. You tin choose to either transform to CommonJS or to preserve the native import
syntax, using node's native ESM support. Configuration is different for each.
Hither is a brief comparison of the two.
CommonJS | Native ECMAScript modules |
---|---|
Write native import syntax | Write native import syntax |
Transforms import into require() | Does not transform import |
Node executes scripts using the classic CommonJS loader | Node executes scripts using the new ESM loader |
Use whatever of:ts-node node -r ts-node/register NODE_OPTIONS="ts-node/register" node crave('ts-node').register({/* options */}) | Employ any of:ts-node --esm ts-node-esm Fix "esm": true in tsconfig.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. Y'all must remove "type": "module"
from package.json
and set "module": "CommonJS"
in tsconfig.json
.
{ // This can be omitted; commonjs is the default "type": "commonjs" }
{ "compilerOptions": { "module": "CommonJS" } }
If yous must proceed "module": "ESNext"
for tsc
, 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'southward ESM loader hooks are experimental 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 information technology is not recommended for product.
For complete usage, limitations, and to provide feedback, run into #1007.
You lot must set "type": "module"
in packet.json
and "module": "ESNext"
in tsconfig.json
.
{ "compilerOptions": { "module": "ESNext" // or ES2015, ES2020 } , "ts-node": { // Tell ts-node CLI to install the --loader automatically, explained beneath "esm": true } }
Y'all must too ensure node is passed --loader
. The ts-node CLI volition do this automatically with our esm
selection.
Note:
--esm
must spawn a child process to laissez passer information technology--loader
. This may modify if node adds the power to install loader hooks into the current procedure.
# pass the flag ts-node --esm # Use the convenience binary ts-node-esm # or add `"esm": truthful` to your tsconfig.json to arrive automated ts-node
If you are not using our CLI, pass the loader flag to node.
node --loader ts-node/esm ./index.ts # Or via environment variable NODE_OPTIONS= "--loader ts-node/esm" node ./index.ts
Troubleshooting
Understanding configuration
ts-node uses sensible default configurations to reduce boilerplate while nonetheless respecting tsconfig.json
if you have ane. If you are unsure which configuration is used, y'all can log it with ts-node --showConfig
. This is similar to tsc --showConfig
but includes "ts-node"
options as well.
ts-node too respects your locally-installed typescript
version, only global installations fallback to the globally-installed typescript
. If you lot are unsure which versions are used, ts-node -vv
will log them.
$ ts-node -vv ts-node v10.0.0 node v16.i.0 compiler v4.2.2 $ ts-node --showConfig { "compilerOptions" : { "target" : "es6" , "lib" : [ "es6" , "dom" ], "rootDir" : "./src" , "outDir" : "./.ts-node" , "module" : "commonjs" , "moduleResolution" : "node" , "strict" : truthful, "announcement" : false, "sourceMap" : truthful, "inlineSources" : true, "types" : [ "node" ], "stripInternal" : true, "incremental" : truthful, "skipLibCheck" : true, "importsNotUsedAsValues" : "error" , "inlineSourceMap" : false, "noEmit" : simulated }, "ts-node" : { "cwd" : "/d/projection" , "projectSearchDir" : "/d/project" , "require" : [], "project" : "/d/project/tsconfig.json" } }
Agreement Errors
Information technology 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 past a type mistake in your code, a bug in your code, or a flaw in your configuration.
TSError
Type errors from the compiler are thrown equally a TSError
. These are the same every bit errors yous get from tsc
.
SyntaxError
Any mistake that is not a TSError
is from node.js (e.g. SyntaxError
), and cannot exist fixed past TypeScript or ts-node. These are bugs in your code or configuration.
Unsupported JavaScript syntax
Your version of node
may not support all JavaScript syntax supported by TypeScript. The compiler must transform this syntax via "downleveling," which is controlled by the tsconfig "target"
pick. Otherwise your code will compile fine, but node will throw a SyntaxError
.
For example, node
12 does non sympathise the ?.
optional chaining operator. If you use "target": "esnext"
, so the following TypeScript syntax:
const bar: cord | undefined = foo ?. bar ;
will compile into this JavaScript:
When you endeavour to run this code, node 12 will throw a SyntaxError
. To fix this, you lot must switch to "target": "es2019"
or lower and then TypeScript transforms ?.
into something node
can understand.
Make it fast
These tricks will brand ts-node faster.
Skip typechecking
It is often better to apply tsc --noEmit
to typecheck once earlier your tests run or as a lint step. In these cases, ts-node tin can skip typechecking.
- Enable
transpileOnly
to skip typechecking - Use our
swc
integration- This is by far the fastest option
With typechecking
- Avoid dynamic
require()
which may trigger repeated typechecking; preferimport
- Endeavour with and without
--files
; one may exist faster depending on your project - Check
tsc --showConfig
; make sure all executed files are included - Enable
skipLibCheck
- Set a
types
array to avoid loading unnecessary@types
Advanced
How It Works
ts-node works by registering hooks for .ts
, .tsx
, .js
, and/or .jsx
extensions.
Vanilla node
loads .js
by reading code from disk and executing it. Our hook runs in the eye, transforming code from TypeScript to JavaScript and passing the result to node
for execution. This transformation will respect your tsconfig.json
as if you lot had compiled via tsc
.
.js
and .jsx
are merely transformed when allowJs
is enabled.
.tsx
and .jsx
are only transformed when jsx
is enabled.
Alert: if a file is ignored or its file extension is non registered, node will either fail to resolve the file or volition endeavor to execute it equally JavaScript without whatsoever transformation. This may cause syntax errors or other failures, because node does not understand TypeScript type syntax nor bleeding-border ECMAScript features.
Warning: When ts-node is used with
allowJs
, all non-ignored JavaScript files are transformed using the TypeScript compiler.
Skipping node_modules
By default, ts-node avoids compiling files in /node_modules/
for three reasons:
- Modules should e'er exist published in a format node.js can consume
- Transpiling the entire dependency tree will make your project slower
- Differing behaviours betwixt TypeScript and node.js (e.m. ES2015 modules) can result in a project that works until y'all decide to back up a feature natively from node.js
If you need to import uncompiled TypeScript in node_modules
, use --skipIgnore
or TS_NODE_SKIP_IGNORE
to featherbed this restriction.
Skipping pre-compiled TypeScript
If a compiled JavaScript file with the same proper noun as a TypeScript file already exists, the TypeScript file will be ignored. ts-node will import the pre-compiled JavaScript.
To strength ts-node to import the TypeScript source, not the precompiled JavaScript, utilize --preferTsExts
.
paths and baseUrl
You can utilize ts-node together with tsconfig-paths to load modules co-ordinate to the paths
section in tsconfig.json
.
{ "ts-node": { // Practise not forget to `npm i -D tsconfig-paths` "require": [ "tsconfig-paths/register" ] } }
Why is this not born to ts-node?
The official TypeScript Handbook explains the intended purpose for "paths"
in "Boosted module resolution flags".
The TypeScript compiler has a set of boosted flags to inform the compiler of transformations that are expected to happen to the sources to generate the terminal output.
It is important to notation that the compiler will not perform any of these transformations; information technology 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 draw mappings that the build tool or runtime already performs, not to tell the build tool or runtime 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 change node
's module resolution beliefs to implement "paths"
mappings.
Help! My Types Are Missing!
ts-node does not use files
, include
or exclude
, past default. This is because a big majority projects do non 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 (due east.g. ts-node index.ts
) and TypeScript resolves dependencies based on imports and references.
For global definitions, you lot can employ the typeRoots
compiler pick. This requires that your type definitions be structured as type packages (non loose TypeScript definition files). More than details on how this works can be institute in the TypeScript Handbook.
Example tsconfig.json
:
{ "compilerOptions": { "typeRoots" : [ "./node_modules/@types" , "./typings" ] } }
Example project structure:
<project_root>/ -- tsconfig.json -- typings/ -- <module_name>/ -- index.d.ts
Instance module declaration file:
declare module '<module_name>' { // module definitions go here }
For module definitions, you lot can employ paths
:
{ "compilerOptions": { "baseUrl": "." , "paths": { "custom-module-blazon": [ "types/custom-module-type" ] } } }
An alternative approach for definitions of 3rd-party libraries are triple-slash directives. This may be helpful if you prefer not to change your TypeScript compilerOptions
or structure your custom type definitions when using typeRoots
. Beneath is an case of the triple-slash directive as a relative path within your project:
/// <reference path="./types/untyped_js_lib" /> import { Greeter } from "untyped_js_lib" const k = new Greeter ( ) ; chiliad . sayHello ( ) ;
Tip: If you must use files
, include
, or exclude
, enable --files
flags or set TS_NODE_FILES=true
.
Third-party compilers
Some projects crave a patched typescript compiler which adds boosted features. For example, ttypescript
and ts-patch
add the ability to configure custom transformers. These are drop-in replacements for the vanilla typescript
module and implement the same API.
For instance, to use ttypescript
and ts-transformer-keys
, add this to your tsconfig.json
:
{ "ts-node": { // This can be omitted when using ts-patch "compiler": "ttypescript" } , "compilerOptions": { // plugin configuration is the aforementioned for both ts-patch and ttypescript "plugins": [ { "transform": "ts-transformer-keys/transformer" } ] } }
Transpilers
In transpile-only mode, we skip typechecking to speed upwards execution time. Y'all tin get a step further and use a 3rd-party transpiler to transform TypeScript into JavaScript even faster. You will still benefit from ts-node'southward automatic tsconfig.json
discovery, sourcemap support, and global ts-node CLI. Integrations can automatically derive an appropriate configuration from your existing tsconfig.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 tin can perform typechecking. A 3rd-party transpiler does not. Both transform TypeScript into JavaScript.
swc
swc back up is born via the --swc
flag or "swc": true
tsconfig option.
swc
is a TypeScript-uniform transpiler implemented in Rust. This makes information technology an order of magnitude faster than vanilla transpileOnly
.
To use it, first install @swc/core
or @swc/wasm
. If using importHelpers
, besides install @swc/helpers
. If target
is less than "es2015" and using either async
/look
or generator functions, also install regenerator-runtime
.
npm i -D @swc/core @swc/helpers regenerator-runtime
Then add the following to your tsconfig.json
.
{ "ts-node": { "swc": truthful } }
swc
uses@swc/helpers
instead oftslib
. If you lot have enabledimportHelpers
, yous must also install@swc/helpers
.
Third-political party transpilers
The transpiler
option allows using third-party transpiler integrations with ts-node. transpiler
must be given the name of a module which can be require()
d. The congenital-in swc
integration is exposed as ts-node/transpilers/swc
.
For example, to use a hypothetical "speedy-ts-compiler", first install information technology into your project: npm install speedy-ts-compiler
So add together the following to your tsconfig:
{ "ts-node": { "transpileOnly": true , "transpiler": "speedy-ts-compiler" } }
Writing your own integration
To write your own transpiler integration, check our API docs.
Integrations are require()
d by ts-node, so they can be published to npm for convenience. The module must export a create
function described by our TranspilerModule
interface. create
is invoked by ts-node at startup to create the transpiler. The transpiler is used repeatedly to transform TypeScript into JavaScript.
Module type overrides
When deciding between CommonJS and native ECMAScript modules, ts-node defaults to matching vanilla node
and tsc
behavior. This means TypeScript files are transformed according to your tsconfig.json
"module"
option and executed according to node'due south rules for the package.json
"type"
field.
In some projects you may need to override this beliefs for some files. For example, in a webpack project, you may have packet.json
configured with "type": "module"
and tsconfig.json
with "module": "esnext"
. However, webpack uses our CommonJS claw to execute your webpack.config.ts
, so you need to force your webpack config and any supporting scripts to execute equally CommonJS.
In these situations, our moduleTypes
option lets you override sure files, forcing execution as CommonJS or ESM. Node supports like overriding via .cjs
and .mjs
file extensions, only .ts
files cannot use them. moduleTypes
achieves the same effect, and also overrides your tsconfig.json
"module"
config appropriately.
The following instance 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 equally tsconfig's "include"
array. When multiple patterns match the same file, the last pattern takes precedence.
-
cjs
overrides matches files to compile and execute equally CommonJS. -
esm
overrides matches files to compile and execute as native ECMAScript modules. -
bundle
resets either of the above to default behavior, which obeysbundle.json
"type"
andtsconfig.json
"module"
options.
Caveats
Files with an overridden module type are transformed with the aforementioned limitations as isolatedModules
. This volition but touch on rare cases such as using const enum
s with preserveConstEnums
disabled.
This 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 ain package.json
to override "type"
. Wherever possible yous should favor using traditional packet.json
and tsconfig.json
configurations.
Recipes
Watching and Restarting
TypeScript Node compiles source code via require()
, watching files and code reloads are out of scope for the projection. If you desire to restart the ts-node
process on file alter, existing node.js tools such as nodemon, onchange and node-dev work.
There'southward too ts-node-dev
, a modified version of node-dev
using ts-node
for compilation that volition restart the process on file change.
AVA
Bold you are configuring AVA via your packet.json
, add one of the following configurations.
CommonJS
Use this configuration if your packet.json
does non have "blazon": "module"
.
{ "ava": { "extensions": [ "ts" ] , "require": [ "ts-node/register" ] } }
Native ECMAScript modules
This configuration is necessary if your package.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
Run into also: https://gulpjs.com/docs/en/getting-started/javascript-and-gulpfiles#transpilation
IntelliJ and Webstorm
Create a new Node.js configuration and add together -r ts-node/register
to "Node parameters."
Notation: If yous are using the --project <tsconfig.json>
command line argument as per the Configuration Options, and desire to apply this same behavior when launching in IntelliJ, specify under "Environment Variables": TS_NODE_PROJECT=<tsconfig.json>
.
Mocha
Mocha seven and newer
mocha --require ts-node/annals --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/annals" , // Specify "loader" for native ESM "loader": "ts-node/esm" , "extensions": [ "ts" , "tsx" ] , "spec": [ "tests/**/*.spec.*" ] , "watch-files": [ "src" ] }
Meet likewise: https://mochajs.org/#configuring-mocha-nodejs
Mocha <=six
mocha --require ts-node/annals --picket-extensions ts,tsx "test/**/*.{ts,tsx}" [...args]
Note: --sentinel-extensions
is only used in --watch
mode.
Tape
ts-node node_modules/tape/bin/record [...args]
Visual Studio Code
Create a new Node.js debug configuration, add -r ts-node/register
to node args and move the program
to the args
listing (so VS Code doesn't look for outFiles
).
{ "configurations": [ { "type": "node" , "asking": "launch" , "name": "Launch Program" , "runtimeArgs": [ "-r" , "ts-node/register" ] , "args": [ "${workspaceFolder}/src/alphabetize.ts" ] } ] , }
Note: If yous are using the --projection <tsconfig.json>
command line statement as per the Configuration Options, and want to use this same behavior when launching in VS Code, add together an "env" key into the launch configuration: "env": { "TS_NODE_PROJECT": "<tsconfig.json>" }
.
Other
In many cases, setting NODE_OPTIONS
will enable ts-node
within other node tools, child processes, and worker threads.
NODE_OPTIONS= "-r ts-node/annals"
Or, if you lot crave native ESM support:
NODE_OPTIONS= "--loader ts-node/esm"
This tells whatever node processes which receive this surround variable to install ts-node
'south hooks before executing other lawmaking.
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
Source: https://www.npmjs.com/package/ts-node
Posted by: shepherdfrocution.blogspot.com
0 Response to "How To Change Order Of Ts Ranks"
Post a Comment