Code Monkey home page Code Monkey logo

ts-node's Introduction

TypeScript Node

NPM version NPM downloads Build status Test 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.js tools and libraries.

Features

  • Automatic sourcemaps in stack traces
  • Automatic tsconfig.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 typescript
npm install -D ts-node

# Or globally with TypeScript.
npm install -g typescript
npm install -g 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

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 --transpileOnly
ts-node-transpile-only script.ts

# Equivalent to ts-node --cwdMode
ts-node-cwd script.ts

# Equivalent to ts-node --esm
ts-node-esm script.ts

Shebang

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

#!/usr/bin/env ts-node

// ts-node options are read from tsconfig.json

console.log("Hello, world!")

Including options within the shebang requires the env -S flag, which is available on recent versions of env. (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 of env 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 and node --loader ts-node/esm

In many cases, setting NODE_OPTIONS will enable ts-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 install ts-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 using require('ts-node').register({ /* options */ }).

Check out our API for more features.

Configuration

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

For a complete list, see Options.

CLI flags

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

$ ts-node --project tsconfig-dev.json say-hello.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 as 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, it is resolved using the same search behavior as tsc. 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 bundled JSON 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 no tsconfig.json is loaded from disk, ts-node will use 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 will use an older default configuration.

When in doubt, ts-node --showConfig will log the configuration being used, and ts-node -vv will log node and typescript versions.

node flags

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

We recommend using the NODE_OPTIONS environment variable to pass options to node.

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

Alternatively, you can invoke node 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 the node.js CLI.

ts-node supports --project and --showConfig similar to the tsc CLI.

Environment variables, where available, are in ALL_CAPS

CLI Options

help

ts-node --help

Prints the help text

version

ts-node -v
ts-node -vvv

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

eval

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

Evaluate code

print

ts-node -p -e <typescript code>
# Example
ts-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 --esm
ts-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 from tsc'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 -c
ts-node --cwdMode
ts-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 resolved tsconfig.json, including ts-node options, and exit

Typechecking

transpileOnly

ts-node -T
ts-node --transpileOnly

Use TypeScript's faster transpileModule

Default: false
Environment: TS_NODE_TRANSPILE_ONLY

typeCheck

ts-node --typeCheck

Opposite of --transpileOnly

Default: true
Environment: TS_NODE_TYPE_CHECK

compilerHost

ts-node -H
ts-node --compilerHost

Use TypeScript's compiler host API

Default: false
Environment: TS_NODE_COMPILER_HOST

files

ts-node --files

Load files, include and exclude from tsconfig.json on startup. This may avoid certain typechecking failures. See Missing 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 with swc. Implies --transpileOnly

Default: false

transpiler

ts-node --transpiler <name>
# Example
ts-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 within scopeDir. 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 when scope is enabled.

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

moduleTypes

Override the module type of certain files, ignoring the package.json "type" field. See Module type overrides for details.

Default: obeys package.json "type" and tsconfig.json "module"
Can only be specified via tsconfig.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 set false to disable

experimentalResolver

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

  • remapping extensions, e.g. so that import "./foo.js" will execute foo.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 to rootDir 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 via tsconfig.json or API.

experimentalSpecifierResolution

ts-node --experimentalSpecifierResolution node

Like node's --experimental-specifier-resolution, but can also be set in your tsconfig.json for convenience. Requires esm to be enabled.

Default: explicit

API Options

The API includes additional 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 vanilla transpileOnly.

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

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

Then add the following to your tsconfig.json.

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

SWC uses @swc/helpers instead of tslib. If you have enabled importHelpers, you must also install @swc/helpers.

CommonJS vs native ECMAScript modules

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

Here 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 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 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. You 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 you must keep "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's 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 it is not recommended for production.

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

You must set "type": "module" in package.json and "module": "ESNext" in tsconfig.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 our esm option.

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

# pass the flag
ts-node --esm
# Use the convenience binary
ts-node-esm
# or add `"esm": true` to your tsconfig.json to make it automatic
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

Configuration

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

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

$ ts-node -vv
ts-node v10.0.0
node v16.1.0
compiler 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 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.

TSError

Type errors from the compiler are thrown as a TSError. These are the same as errors you get from tsc.

SyntaxError

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

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" option. Otherwise your code will compile fine, but node will throw a SyntaxError.

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

const bar: string | undefined = foo?.bar;

will compile into this JavaScript:

const a = foo?.bar;

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

ERR_REQUIRE_ESM

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

  • 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 as webpack.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" configuration Docs
    • 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 as mocha.
    • 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: Use ts-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 as webpack.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 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.

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

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

Example tsconfig.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 use paths:

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

Another option is triple-slash directives. 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:

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

If none of the above work, and you must use files, include, or exclude, enable our files option.

npx, yarn dlx, and node_modules

When executing TypeScript with npx or yarn dlx, the code resides within a temporary node_modules directory.

The contents of node_modules are ignored by default. If execution fails, enable skipIgnore.

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 run tsc --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:

  • Enable swc
    • This is by far the fastest option
  • Enable transpileOnly to skip typechecking without swc

With typechecking

If you absolutely must typecheck in ts-node:

  • Avoid dynamic require() which may trigger repeated typechecking; prefer import
  • Try with and without --files; one may be 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 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.

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 various options 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 when allowJs is enabled.

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

Warning:

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

Skipping node_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 in node_modules, use --skipIgnore or TS_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

Our scope and scopeDir options will limit transformation to files within a directory.

Ignore by regexp

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

paths and baseUrl

You can use ts-node together with tsconfig-paths to load modules according to the paths section in tsconfig.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 to inform 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 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 modify node'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 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 example, 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 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 JavaScript much faster than the TypeScript compiler. You will still benefit from ts-node's automatic tsconfig.json discovery, sourcemap support, and global ts-node CLI. Plugins 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 can perform typechecking. A third-party transpiler does not. Both transform TypeScript into JavaScript.

Third-party plugins

The transpiler option allows using third-party transpiler plugins with ts-node. transpiler must be given the name of a module which can be require()d. The built-in swc plugin is exposed as ts-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 our API docs.

Plugins are require()d by ts-node, so they can be a local script or a node module published to npm. The module must export a create function described by our TranspilerModule interface. create is invoked by ts-node at startup to create one or more transpiler instances. The instances are used to transform TypeScript 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's NodeNext or Node16 mode instead of the options described in 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 matches node and tsc behavior. This means TypeScript files are transformed according to your tsconfig.json "module" option and executed according to node's rules for the package.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 a name-of-tool.config.ts and require that file to execute as CommonJS. If you have package.json configured with "type": "module" and tsconfig.json with "module": "esnext", the config is native ECMAScript by default and will raise an error. You will need to force the config and any supporting scripts to execute as CommonJS.

In these situations, our moduleTypes option can override certain files to be CommonJS 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, and also overrides your tsconfig.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 obeys package.json "type" and tsconfig.json "module" options.

Caveats

Files with an overridden module type are transformed with the same limitations as isolatedModules. This will only affect rare cases such as using const enums 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 own package.json to override "type". Wherever possible you should favor using traditional package.json and tsconfig.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 without registering any hooks.
  • createRepl() creates an instance of our REPL service, so you 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 the ts-node process on file change, existing node.js tools such as nodemon, onchange and node-dev work.

There's also ts-node-dev, a modified version of 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.

AVA

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

CommonJS

Use this configuration if your package.json does not have "type": "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

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 the Configuration 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 the program to the args list (so VS Code doesn't look for outFiles).

{
    "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 the Configuration 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, setting NODE_OPTIONS will enable ts-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 install ts-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

ts-node's People

Contributors

3mard avatar basarat avatar blakeembrey avatar burnnat avatar chrisleck avatar concision avatar cspotcode avatar cthrax avatar dependabot[bot] avatar devversion avatar ejose19 avatar g-rath avatar greenkeeper[bot] avatar greenkeeperio-bot avatar jonaskello avatar jontem avatar musahaidari avatar naridal avatar papb avatar paulbrimicombe avatar pokute avatar queengooborg avatar rakannimer avatar rharriso avatar rsxdalv avatar srolel avatar stelcheck avatar sylc avatar theunlocked avatar unional avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ts-node's Issues

"Failed to load external module ts-node/register" on Travis CI build

Hi,

I'm trying to test a generator project and I'm receiving errors when my gulpfiles are written in TypeScript.

You can look at the logs of the tests on Travis. It fails to load the ts-node/register module to parse the gulpfile.ts.

Everything seems to work fine on node 5 and higher but it fails to load the ts-node/register module on node versions below that. On my local machine (node v4.2.1) everything works fine.

Do you know what the reason could be? I'm trying to run the following testfile.

Performance issues

Are there known performance issues of ts-node? I have a medium sized typescript project and we used to compile with tsc and then run tests with mocha. However, ts-node seems to be better because we a) don't need to have a plugin to support sourcemaps and b) generate js and js.map files before we run the tests. So I tried ts-node with mocha in gulp but now builds take ~20s. I suspect that this is because all the files have to be recompiled. Is this a known issue?

Allow `disableWarnings` to be set by environment variable

I've been looking at #44 and I noticed that one of the things you want to do is make it fast and production-ready. I'm really excited about this, but I realize that a lot of time is involved in a rewrite and that I can't realistically expect this to be done in the near future (although I'd be happy to help).

I'm working on a tool called node-script (https://github.com/joeskeen/node-script), which allows you to create self-contained Node scripts (not requiring a package.json file or running npm install first). One of the big things I'm in the process of tackling before v1.0 is transpiler support. I'm currently using the interpret module to determine which packages are required to register the script file. Currently ts-node is first in line for the ts file extension, so that is the one that node-script calls upon to run TypeScript node-scripts. The issue comes when I copy the script file to another location to run it in isolation. Removed from its home during development, the script's /// <reference /> comments and other typing resolution no longer resolves. Since interpret points me directly to require('ts-node/register'), I can't call require('ts-node').register({options}) without making a special case.

If ts-node's register function was able to pick up whether to disableWarnings from process.env or something similar, I could make sure that that is set before require('ts-node/register') is called.

I think that this could be a good workaround until the new production-ready version of ts-node is ready.

Incorrect order of extend()ing compilerOptions

In ts-node.ts around line 80,

  config.compilerOptions = extend({
    target: 'es5',
    module: 'commonjs'
  }, config.compilerOptions, {
    sourceMap: true,
    inlineSourceMap: false,
    inlineSources: false,
    declaration: false
  })

should be

  config.compilerOptions = extend({
    sourceMap: true,
    inlineSourceMap: false,
    inlineSources: false,
    declaration: false
  }, config.compilerOptions, {
    target: 'es5',
    module: 'commonjs'
  })

for { target: 'es5', module: 'commonjs' } to take precedence over user's options, which potentially may be intended for latest browsers environments.

SyntaxError: Unexpected token ...

Error token "..." but not error compile by tsc

SyntaxError: Unexpected token ...
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:374:25)
at Object.loader (D:\project\node_modules\ts-node\src\ts-node.ts:225:14)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Module.require (module.js:354:17)
at require (internal/module.js:12:17)
....

tsconfig.ts

"compilerOptions": {
"target": "es5",
"jsx": "react",
"module": "commonjs"
}

environment
typescript: 1.8.2
ts-node: 0.5.5

Shebang support

Would be awesome to be able to use ts-node as a shebang script:

#!/usr/bin/env ts-node
console.log('ohai from TypeScript');

`--` arg disappears

First off, thanks for creating and maintaining ts-node. It is awesome!

Consider the following Node script args.js:

console.log(process.argv)

Calling this with node, we get the following result:

>node args hi -- test -a
[ 'C:\\Program Files\\nodejs\\node.exe',
  'C:\\temp\\args',
  'hi',
  '--',
  'test',
  '-a' ]

But if you call it using ts-node, you lose the -- argument:

>ts-node args hi -- test -a
[ 'node', 'C:\\temp\\args', 'hi', 'test', '-a' ]

I came across this when trying to use yargs to parse command line arguments. yargs considers the -- argument as a signal to stop parsing arguments and take the rest of the arguments as string literals rather than switches. When running it through ts-node, the -- disappears, so arguments that should be taken literally are being parsed as switches. I can overcome this by passing -- --, but I think it would be better to have a consistent behavior between node and ts-node for interoperability.

Add ability to configure TypeScript Node from tsconfig.json

Since the module could end up being used in a lot of different environments (E.g. gulp), there should be a way to configure it via config file or environment. Since tsconfig.json already exists, I'd say we piggy back off it and add a typescript-node property to the object.

noEmit option in tsconfig

Hi there,

when using ts-node/register via interpret on .ts files, AND using noEmit:true in tsconfig.json, it works just fine for typescript 1.7.3., but gives an error for typescript 1.8.0:

Requiring external module ts-node/register

⨯ Unable to compile TypeScript

gulpfile.ts: Emit skipped

It would be nice if we could get this to work again, because otherwise I can't get my IDE to shut-up (= not compile files, that I want my gulp to produce instead).

TypeError: Cannot read property 'text' of undefined

I'm getting an error

[10:28:53] Requiring external module ts-node/register

    project/node_modules/ts-node/dist/ts-node.js:68
            var result = output.outputFiles[1].text;
                                              ^
    TypeError: Cannot read property 'text' of undefined
        at getOutput (project/node_modules/ts-node/dist/ts-node.js:68:43)
        at compile (project/node_modules/ts-node/dist/ts-node.js:91:16)
        at Object.loader (project/node_modules/ts-node/dist/ts-node.js:94:27)
        at Module.load (module.js:355:32)
        at Function.Module._load (module.js:310:12)
        at Module.require (module.js:365:17)
        at require (module.js:384:17)
        at Liftoff.handleArguments (project/node_modules/gulp/bin/gulp.js:116:3)
        at Liftoff.<anonymous> (project/node_modules/gulp/node_modules/liftoff/index.js:192:16)
        at module.exports (project/node_modules/gulp/node_modules/liftoff/node_modules/flagged-respawn/index.js:17:3)

I've made a snapshot of the project here alexgorbatchev/gulp-typescript-webpack-react-hotreload@d6fc57f . Try running gulp dev.

Not refreshing code with mocha --watch

I've tried to use this module as mocha --compilers tsx:typescript-node/register and it works great, but when I add --watch, it will always run the same code as the first run of mocha. I suspect it's caching the compiled files and not recompiling until running again.

I'm using it with typescript@next (1.6.0-dev.20150908) and .tsx files (for JSX support).

When I was using babel compiler for my js tests, --compilers js:babel/register, was working fine.

Persist REPL types between execution

Currently each REPL line replaces the previous and all type information is lost. Not very useful at all. First thoughts are to concat each line and pass it through the TypeScript compiler, then using diff to execute the new code paths.

Replace language services with program usage

The REPL would still need to use the language services API (to use .type, for example), but the execution environment can avoid it. It should be possible to create a program with the compiler options and write all the files into a tmp directory (or into memory?). When reading again (from node, this time) we check the modtime in the tmp directory vs the current file and either read from cache or re-compile using TypeScript and output diagnostics.

What's the downsides of either approach?

From #16.

error [email protected] postinstall: `typings install`

It looks like we have to install typings now, so I did ("npm install -g typings"), but when I try to install ts-node I get the following:

2813 verbose stack Error: [email protected] postinstall: `typings install`
2813 verbose stack Exit status 1
2813 verbose stack     at EventEmitter.<anonymous> (C:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\lifecycle.js:214:16)
2813 verbose stack     at emitTwo (events.js:87:13)
2813 verbose stack     at EventEmitter.emit (events.js:172:7)
2813 verbose stack     at ChildProcess.<anonymous> (C:\Program Files (x86)\nodejs\node_modules\npm\lib\utils\spawn.js:24:14)
2813 verbose stack     at emitTwo (events.js:87:13)
2813 verbose stack     at ChildProcess.emit (events.js:172:7)
2813 verbose stack     at maybeClose (internal/child_process.js:818:16)
2813 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
2814 verbose pkgid [email protected]
2815 verbose cwd C:\updraft
2816 error Windows_NT 6.1.7601
2817 error argv "C:\\Program Files (x86)\\nodejs\\node.exe" "C:\\Program Files (x86)\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "--save-dev" "ts-node"
2818 error node v4.1.2
2819 error npm  v2.14.4
2820 error code ELIFECYCLE
2821 error [email protected] postinstall: `typings install`
2821 error Exit status 1
2822 error Failed at the [email protected] postinstall script 'typings install'.
2822 error This is most likely a problem with the ts-node package,
2822 error not with npm itself.
2822 error Tell the author that this fails on your system:
2822 error     typings install
2822 error You can get their info via:
2822 error     npm owner ls ts-node
2822 error There is likely additional logging output above.
2823 verbose exit [ 1, true ]
2824 verbose unbuild node_modules\ts-node
2825 info preuninstall [email protected]
2826 info uninstall [email protected]
2827 verbose unbuild rmStuff [email protected] from C:\updraft\node_modules
2828 silly gentlyRm C:\updraft\node_modules\.bin\ts-node.cmd is being gently removed
2829 silly gentlyRm verifying C:\updraft is an npm working directory
2830 silly gentlyRm containing path C:\updraft is under npm's control, in C:\updraft
2831 silly gentlyRm deletion target C:\updraft\node_modules\.bin\ts-node.cmd is under C:\updraft
2832 verbose gentlyRm vacuuming from C:\updraft\node_modules\.bin\ts-node.cmd up to C:\updraft
2833 silly vacuum-fs removing C:\updraft\node_modules\.bin\ts-node.cmd
2834 silly vacuum-fs quitting because other entries in C:\updraft\node_modules\.bin
2835 silly gentlyRm C:\updraft\node_modules\.bin\ts-node is being gently removed
2836 silly gentlyRm verifying C:\updraft is an npm working directory
2837 silly gentlyRm containing path C:\updraft is under npm's control, in C:\updraft
2838 silly gentlyRm deletion target C:\updraft\node_modules\.bin\ts-node is under C:\updraft
2839 verbose gentlyRm vacuuming from C:\updraft\node_modules\.bin\ts-node up to C:\updraft
2840 silly vacuum-fs removing C:\updraft\node_modules\.bin\ts-node
2841 silly vacuum-fs quitting because other entries in C:\updraft\node_modules\.bin
2842 info postuninstall [email protected]
2843 silly gentlyRm C:\updraft\node_modules\ts-node is being purged from base C:\updraft
2844 verbose gentlyRm don't care about contents; nuking C:\updraft\node_modules\ts-node
2845 silly vacuum-fs purging C:\updraft\node_modules\ts-node
2846 silly vacuum-fs quitting because other entries in C:\updraft\node_modules

`jsdom-global` compatibility

Thanks for writing ts-node for TypeScript register!

Hi, I'm writing browser mock test in jsdom.
The source code relies heavily on DOM and BOM, so I opted jsdom-global for better import behavior.

Both my source code and test code are written in TypeScript. And I use ts-node for ts extension register.

However, it seems jsdom-global breaks ts-node (or vice-versa). Something wrong with sourcemap.

Minimal setup:

npm install mocha ts-node jsdom jsdom-global
tsd install mocha node

Test code:

/// <reference path='../typings/tsd.d.ts' />

import * as assert from 'assert'
// import jsdom from 'jsdom-global'
var jsdom = require('jsdom-global')
jsdom()

describe('test sourcemap', () => {
    it('should report sourcemap', () => {
        assert(false)
    })
})
> mocha --compilers ts:ts-node/register
/tmp/node_modules/source-map-support/source-map-support.js:407
      var hasStack = (arguments[1] && arguments[1].stack);
TypeError: Invalid URL
npm ERR! Test failed.  See above for more details.

And when I changed the compiler to babel (and test file extension to js). Error is reported as expected.

> mocha --compilers js:babel-register



  test sourcemap
    1) should report sourcemap


  0 passing (46ms)
  1 failing

  1) test sourcemap should report sourcemap:

      AssertionError: false == true
      + expected - actual

      -false
      +true

      at Context.<anonymous> (index.js:10:3)

Show warnings but still run

Sometimes you want to just run something, while still displaying the warnings (e.g., missing type definitions) that you should fix once that your implementation is working.

ts-node tries to compile .scss files

Hello,

I tried to add my styles via require in my components like
require('./App.scss');

But I get this error:
SyntaxError: Unexpected token .
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:413:25)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)

Is there any chance I can mark them to exclude?

Improve error messages

When compiling TypeScript at runtime or in the REPL, or even in the CLI, there's no need to throw errors with a stack trace. The errors could also use some colour with the output to easily identify issues.

ReferenceError: MyClass is not defined

I have the following files;

MyClass.ts

class MyClass {
    x: number;
    y: number;
    constructor(x: number, y :number) {
        this.x = x;
        this.y = y;
    }
}

MyScript.ts

/// <reference path="MyClass.ts" />
var myClass: MyClass = new MyClass(2,3);
console.log(myClass.x, myClass.y);

Compiling via tsc is successful, however I cannot execute MyScript.cs with ts-node. Am I doing something wrong?

c:\git\ts-node-test>tsc MyScript.ts

c:\git\ts-node-test>ts-node -v
0.5.5

c:\git\ts-node-test>ts-node MyScript.js

c:\Users\stafford\Documents\git\ts-node-test\MyScript.js:2
var myClass = new MyClass(2, 3);
                  ^
ReferenceError: MyClass is not defined
    at Object.<anonymous> (c:\Users\stafford\Documents\git\ts-node-test\MyScript.js:2:19)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at Object.<anonymous> (C:\Users\stafford\AppData\Roaming\npm\node_modules\ts-node\src\bin\ts-node.ts:121:12)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)

c:\git\ts-node-test>

Repro

Excluded files in tsconfig.json sometimes not honored

Hi again :)

I noticed some weird behavior while running some tests on travis. It seems that the exclude property in tsconfig.json is sometimes not honored.

This here is the failing test on travis. You can see that it complains about duplicate typings, although jspm_packages is excluded in the tsconfig.json. Also, this test here passes without any errors although they are both run from the same codebase.

Is this a bug or do I have a faulty configuration?

TypeScript Node 1.0

From the issues I've seen logged thus far, I'm looking at rewriting ts-node into something that can suit more people. Here's some of the points that need covering for 1.0. Comments are appreciated.

  • The goal is to be fast and production-ready out of the box (breaking change)
    • This means no type information, because that requires loading the entire project into memory
    • All files will transpile directly, in-memory using TypeScript transpileModule
    • Can enable a cache directory for a simple speed up
  • One level up, semi-production ready, is the --typed flag
    • This transpiles the entire project and caches it once on startup
    • This has type information, but only for things in the initial project/require - subsequent requires of TypeScript files would fall back to the first point
  • The next level, non production ready, is the --fully-typed flag
    • This is basically the current version of ts-node, suitable for a test suite
    • Everything needs to be in-memory because require can be "out-of-band". E.g. .ts -> .js -> .ts, not possible to handle by just the TypeScript compiler
    • We can think about way to fix this "out of band" require issue, but I believe changed files should always be re-loaded correctly (E.g. watching a test suite should get new diagnostics without re-compiling everything) /cc @basarat Any thoughts on this point? Maybe a way to serialize the compiler state in some form?
  • The project flag is disabled by default (still considering this)
    • Enable ability to specify directory or file
  • Compiler option flag - specify TypeScript compiler options via JSON
  • All flags should have an environment variable for environments that can't specific CLI flags - E.g. Gulp, Grunt, etc.

es6 compile errors with no location information

I'm trying to switch over to the latest typescript so that I can use async/await inside a mocha test. My tsconfig specifies es6 and module commonjs. If I run tsc from the command-line it reports no errors, but when I run from gulp (which registers ts-node) I get this error.

[15:15:17] Using gulpfile C:\updraft\Gulpfile.js
[15:15:17] Starting 'test'...
[15:15:20] 'test' errored after 3.03 s
[15:15:20] SyntaxError in plugin 'gulp-mocha'
Message:
    Block-scoped declarations (let, const, function, class) not yet supported outside strict mode Stack:
SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:413:25)
    at Object.loader (C:\updraft\node_modules\ts-node\dist\ts-node.js:102:18)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (C:\updraft\src\index.ts:1:20)
    at Module._compile (module.js:434:26)
    at Object.loader (C:\updraft\node_modules\ts-node\dist\ts-node.js:102:18)

So problem (1) is that there shouldn't be a difference between tsc and ts-node (I have typescript@next installed locally and globally), and (2) is that the output gives no indication of where (file/line) the error was found

Ignore arguments after filename with CLI

Currently, the arguments are all parsed instead of just up to the first filename. This can easily by fixed by first slicing the argv array and then evaluating it.

Rebrand to `ts-node`?

The command line interface is ts-node, which is inconsistent with the package name. Should I make the CLI longer (unlikely, too much to type), rename the package for consistency or ignore it?

doesn't work with typescript@next

/Users/aolson/Developer/updraft/node_modules/ts-node/dist/ts-node.js:32
    return ts.parseConfigFile(config, ts.sys, fileName);
              ^

TypeError: ts.parseConfigFile is not a function
    at readConfig (/Users/aolson/Developer/updraft/node_modules/ts-node/dist/ts-node.js:32:15)
    at Object.register (/Users/aolson/Developer/updraft/node_modules/ts-node/dist/ts-node.js:41:18)
    at Object.<anonymous> (/Users/aolson/Developer/updraft/Gulpfile.js:55:20)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Liftoff.handleArguments (/usr/local/lib/node_modules/gulp/bin/gulp.js:116:3)

looks like they renamed parseConfigFile to parseJsonConfigFileContent

ts-node "compiles" all TypeScript files upon boot up

I'm using ts-node to get gulpfile.ts to work and it appears that ts-node compiles all TypeScript files when gulp starts. If I have errors in clientside files that aren't required anywhere in the gulpfile.ts file, gulp still fails to start because ts-node fails with TypeScript errors.

I have my clientside files linked in tsconfig.json, which might be causing this side effect. I'm worried that eventually when the project gets larger it will become a real problem because ts-node will unnecessarily compile all TypeScript files.

Is it possible to use both ts-node/register and babel-core/register?

Hi,
I have a question: is it possible to use ts-node/register followed by babel-core/register?

My goal is to have typescript configured to output es6, and then have babel do the es6 to es5 conversion. Thus, I would be able to use typescript interfaces where needed, but still integrate with other parts of the code using ES6 javascript.

Putting the two requires in my index.js does not raise any error, but also does not have the intended behaviour - I get different outputs if I just run node index.js, or if I manually run tsc first and then run node index.js - the difference being, IMHO, that the second case passes the js files outputed by the typescript compiler through babel, while the first case doesn't.

For reference:

index.js

require('babel-core/register');
require('ts-node/register'); 
require('./Tasks');

tsconfig.json

{
    "compilerOptions": {
        "target":"es6"
    },
    "files": 
        ["Databases.ts"
        ,"Tasks.ts"
        ]
}

Add documentation on Gulp usage

From #24. Should also clarify that certain issues are coming from node and that this always loads tsconfig.json by default - how to use two tsconfig.json files.

noLib option not observed

In order to use ES6 features but compile down to ES5 I am using the following config options in tsconfig.json:

compilerOptions: {
   target: 'es5',
   noLib: true,
},
files: [
  'node_modules/typescript/lib/lib.es6.d.ts',
   ...
]

however this causes loads of 'duplicate identifier' compiler errors because ts-node is not observing the noLib option here

TypeScript 1.7.x TypeError: ts.parseConfigFile is not a function

I am using typescript@next and got following error:

/Developer/Work/node/koa-router-decorators/node_modules/ts-node/dist/ts-node.js:32
    return ts.parseConfigFile(config, ts.sys, fileName);
              ^

TypeError: ts.parseConfigFile is not a function
    at readConfig (/Developer/Work/node/koa-router-decorators/node_modules/ts-node/dist/ts-node.js:32:15)
    at Object.register (/Developer/Work/node/koa-router-decorators/node_modules/ts-node/dist/ts-node.js:41:18)
    at Object.<anonymous> (/Developer/Work/node/koa-router-decorators/node_modules/ts-node/register.js:1:77)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Module.require (module.js:366:17)
    at require (module.js:385:17)
    at /Developer/Work/node/koa-router-decorators/node_modules/mocha/bin/_mocha:296:3
    at Array.forEach (native)
    at Object.<anonymous> (/Developer/Work/node/koa-router-decorators/node_modules/mocha/bin/_mocha:290:19)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:134:18)
    at node.js:961:3

Version?

Hi, wondering what version of Typescript is currently supported?

Mocha issues when running multiple test files

Hi!

I love ts-node so far but I run into issues when I want to run multiple tests at once. You can check out a sample repository to reproduce the error.

I have three tests and two test scripts declared in package.json. When I run

npm run test-single

# test-single: mocha test/test.ts --require ts-node/register && mocha test/test3.ts --require ts-node/register && mocha test/newtest.ts --require ts-node/register

it will execute each test one by one and everything seems to work fine. However, if I run all tests within one mocha run, like

npm test

# test: mocha test/**/*.ts --require ts-node/register

I receive the following TypeScript compilation errors from ts-node:

> [email protected] test /usr/local/src/Misc/ts-node-mocha
> mocha test/**/*.ts --require ts-node/register

----------------------------------
⨯ Unable to compile TypeScript

test/newtest.ts (5,14): Property 'should' does not exist on type 'string'. (2339)
test/test.ts (5,14): Property 'should' does not exist on type 'string'. (2339)
typings/should/should.d.ts (125,12): Cannot find name 'should'. (2304)
----------------------------------
npm ERR! Test failed.  See above for more details.

What am I doing wrong? I'd really like to test all files within a folder at once.

syntax error in default parameter

Hi, I cannot use default parameter

// hello.ts
function hello(name = 'World') {
    console.log(`Hello, ${name}`)
}
$ ts-node hello.ts
SyntaxError: Unexpected token =
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:374:25)
    at Object.loader (/sandbox/node_modules/ts-node/src/ts-node.ts:225:14)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at Object.<anonymous> (/sandbox/node_modules/ts-node/src/bin/ts-node.ts:121:12)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)

below code works fine

function hello(name) {
    console.log(`Hello, ${name}`)
}

environment

  • node: 5.4.0
  • typescript: 1.7.5
  • tsconfig.json
{
    "compilerOptions": {
        "target": "es6",
        "noImplicitAny": false,
        "sourceMap": false
    },
    "exclude": [ "node_modules" ]
}

thanks.

can't run in existing project with node_modules

For some reason command line ts-node seems to search the local node_modules folder even when there are no references to it in the file you run. Also, if I run ts-node to get a REPL and execute any command inside a project that has typescript in it, but also have typescript installed globally, I get thousands of duplicate identifier errors.

If I remove typescript from the local project, I get node_modules/autoprefixer-loader/node_modules/postcss/postcss.d.ts (2,22): Cannot find module 'd.ts/postcss'. (2307) node_modules/autoprefixer-loader/node_modules/postcss/postcss.d.ts (3,2): Duplicate identifier 'default'. (2300)

so it appears to search my node_modules folder for all kinds of definitions and then throw a bunch of errors before it evaluates the first line of typescript. I get the same errors running an empty typescript file. Is this expected behavior?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.