Socket
Socket
Sign inDemoInstall

ts-node

Package Overview
Dependencies
Maintainers
1
Versions
128
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-node - npm Package Compare versions

Comparing version 5.0.1 to 6.0.0

register/transpile-only.js

57

dist/bin.js

@@ -18,3 +18,3 @@ #!/usr/bin/env node

string: ['eval', 'print', 'compiler', 'project', 'ignoreDiagnostics', 'require', 'cacheDirectory', 'ignore'],
boolean: ['help', 'typeCheck', 'version', 'cache', 'skipProject', 'skipIgnore'],
boolean: ['help', 'transpileOnly', 'typeCheck', 'version', 'cache', 'skipProject', 'skipIgnore'],
alias: {

@@ -27,2 +27,3 @@ eval: ['e'],

typeCheck: ['type-check'],
transpileOnly: ['transpile-only'],
cacheDirectory: ['cache-directory'],

@@ -40,2 +41,3 @@ ignore: ['I'],

typeCheck: index_1.DEFAULTS.typeCheck,
transpileOnly: index_1.DEFAULTS.transpileOnly,
skipIgnore: index_1.DEFAULTS.skipIgnore,

@@ -46,3 +48,3 @@ skipProject: index_1.DEFAULTS.skipProject

if (argv.help) {
console.log("\nUsage: ts-node [options] [ -e script | script.ts ] [arguments]\n\nOptions:\n\n -e, --eval [code] Evaluate code\n -p, --print [code] Evaluate code and print result\n -r, --require [path] Require a node module before execution\n\n -h, --help Print CLI usage\n -v, --version Print module version information\n\n --type-check Enable type checking through CLI\n --cache-directory Configure the output file cache directory\n -I, --ignore [pattern] Override the path patterns to skip compilation\n -P, --project [path] Path to TypeScript JSON project file\n -C, --compiler [name] Specify a custom TypeScript compiler\n -D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code\n -O, --compilerOptions [opts] JSON object to merge with compiler options\n\n --no-cache Disable the local TypeScript Node cache\n --skip-project Skip project config resolution and loading\n --skip-ignore Skip ignore checks\n");
console.log("\nUsage: ts-node [options] [ -e script | script.ts ] [arguments]\n\nOptions:\n\n -e, --eval [code] Evaluate code\n -p, --print [code] Evaluate code and print result\n -r, --require [path] Require a node module before execution\n\n -h, --help Print CLI usage\n -v, --version Print module version information\n\n -T, --transpile-only Use TypeScript's faster `transpileModule`\n --cache-directory Configure the output file cache directory\n -I, --ignore [pattern] Override the path patterns to skip compilation\n -P, --project [path] Path to TypeScript JSON project file\n -C, --compiler [name] Specify a custom TypeScript compiler\n -D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code\n -O, --compilerOptions [opts] JSON object to merge with compiler options\n\n --no-cache Disable the local TypeScript Node cache\n --skip-project Skip reading `tsconfig.json`\n --skip-ignore Skip `--ignore` checks\n");
process.exit(0);

@@ -52,6 +54,8 @@ }

var code = argv.eval === undefined ? argv.print : argv.eval;
var isEval = typeof argv.eval === 'string' || !!argv.print;
var isEval = typeof argv.eval === 'string' || !!argv.print; // Minimist struggles with empty strings.
var isPrinted = argv.print !== undefined;
// Register the TypeScript compiler instance.
var service = index_1.register({
typeCheck: argv.typeCheck,
transpileOnly: argv.transpileOnly,
cache: argv.cache,

@@ -69,2 +73,3 @@ cacheDirectory: argv.cacheDirectory,

});
// Output project information.
if (argv.version) {

@@ -77,6 +82,11 @@ console.log("ts-node v" + index_1.VERSION);

}
// Require specified modules before start-up.
Module._preloadModules(arrify(argv.require));
/**
* Eval helpers.
*/
var EVAL_FILENAME = "[eval].ts";
var EVAL_PATH = path_1.join(cwd, EVAL_FILENAME);
var EVAL_INSTANCE = { input: '', output: '', version: 0, lines: 0 };
// Execute the main contents (either eval, script or piped).
if (isEval) {

@@ -92,2 +102,3 @@ evalAndExit(code, isPrinted);

else {
// Piping of execution _only_ occurs when no other script is specified.
if (process.stdin.isTTY) {

@@ -103,2 +114,5 @@ startRepl();

}
/**
* Evaluate a script.
*/
function evalAndExit(code, isPrinted) {

@@ -128,2 +142,5 @@ var module = new Module(EVAL_FILENAME);

}
/**
* Evaluate the code snippet.
*/
function _eval(input, context) {

@@ -141,2 +158,3 @@ var lines = EVAL_INSTANCE.lines;

}
// Use `diff` to check for new JavaScript to execute.
var changes = diff_1.diffLines(EVAL_INSTANCE.output, output);

@@ -153,2 +171,5 @@ if (isCompletion) {

}
/**
* Execute some code.
*/
function exec(code, filename, context) {

@@ -158,2 +179,5 @@ var script = new vm_1.Script(code, { filename: filename });

}
/**
* Start a CLI REPL.
*/
function startRepl() {

@@ -167,5 +191,7 @@ var repl = repl_1.start({

});
// Bookmark the point where we should reset the REPL state.
var resetEval = appendEval('');
function reset() {
resetEval();
// Hard fix for TypeScript forcing `Object.defineProperty(exports, ...)`.
exec('exports = module.exports', EVAL_FILENAME, repl.context);

@@ -190,5 +216,9 @@ }

}
/**
* Eval code from the REPL.
*/
function replEval(code, context, _filename, callback) {
var err;
var result;
// TODO: Figure out how to handle completion here.
if (code === '.scope') {

@@ -203,2 +233,3 @@ callback();

if (error instanceof index_1.TSError) {
// Support recoverable compilations using >= node 6.
if (repl_1.Recoverable && isRecoverable(error)) {

@@ -217,2 +248,5 @@ err = new repl_1.Recoverable(error);

}
/**
* Append to the eval instance and return an undo function.
*/
function appendEval(input) {

@@ -223,2 +257,3 @@ var undoInput = EVAL_INSTANCE.input;

var undoLines = EVAL_INSTANCE.lines;
// Handle ASI issues with TypeScript re-evaluation.
if (undoInput.charAt(undoInput.length - 1) === '\n' && /^\s*[\[\(\`]/.test(input) && !/;\s*$/.test(undoInput)) {

@@ -237,2 +272,5 @@ EVAL_INSTANCE.input = EVAL_INSTANCE.input.slice(0, -1) + ";\n";

}
/**
* Count the number of lines.
*/
function lineCount(value) {

@@ -248,2 +286,5 @@ var count = 0;

}
/**
* Get the file text, checking for eval first.
*/
function readFileEval(path) {

@@ -255,4 +296,7 @@ if (path === EVAL_PATH)

}
catch (err) { }
catch (err) { /* Ignore. */ }
}
/**
* Get whether the file exists.
*/
function fileExistsEval(path) {

@@ -275,4 +319,7 @@ if (path === EVAL_PATH)

1160,
1161
1161 // "Unterminated regular expression literal."
];
/**
* Check if a function can recover gracefully.
*/
function isRecoverable(error) {

@@ -279,0 +326,0 @@ return error.diagnostics.every(function (x) { return RECOVERY_CODES.indexOf(x.code) > -1; });

import { BaseError } from 'make-error';
import * as TS from 'typescript';
/**
* Common TypeScript interfaces between versions.
*/
export interface TSCommon {

@@ -19,5 +22,12 @@ version: typeof TS.version;

}
/**
* Export the current version.
*/
export declare const VERSION: any;
/**
* Registration options.
*/
export interface Options {
typeCheck?: boolean | null;
transpileOnly?: boolean | null;
cache?: boolean | null;

@@ -36,2 +46,5 @@ cacheDirectory?: string;

}
/**
* Information retrieved from type info check.
*/
export interface TypeInfo {

@@ -41,6 +54,21 @@ name: string;

}
/**
* Default register options.
*/
export declare const DEFAULTS: Options;
/**
* Split a string array of values.
*/
export declare function split(value: string | undefined): string[] | undefined;
/**
* Parse a string as JSON.
*/
export declare function parse(value: string | undefined): object | undefined;
/**
* Replace backslashes with forward slashes.
*/
export declare function normalizeSlashes(value: string): string;
/**
* TypeScript diagnostics error.
*/
export declare class TSError extends BaseError {

@@ -51,2 +79,5 @@ diagnostics: TSDiagnostic[];

}
/**
* Return type for registering `ts-node`.
*/
export interface Register {

@@ -60,4 +91,13 @@ cwd: string;

}
/**
* Register TypeScript compiler.
*/
export declare function register(opts?: Options): Register;
/**
* Format an array of diagnostics.
*/
export declare function formatDiagnostics(diagnostics: TS.Diagnostic[], cwd: string, ts: TSCommon, lineOffset: number): TSDiagnostic[];
/**
* Internal diagnostic representation.
*/
export interface TSDiagnostic {

@@ -67,3 +107,9 @@ message: string;

}
/**
* Format a diagnostic object into a string.
*/
export declare function formatDiagnostic(diagnostic: TS.Diagnostic, cwd: string, ts: TSCommon, lineOffset: number): TSDiagnostic;
/**
* Stringify the `TSError` instance.
*/
export declare function printError(error: TSError): string;

@@ -34,3 +34,9 @@ "use strict";

function (_, fn) { return fn; };
/**
* Export the current version.
*/
exports.VERSION = pkg.version;
/**
* Default register options.
*/
exports.DEFAULTS = {

@@ -46,4 +52,8 @@ cache: yn(process.env['TS_NODE_CACHE'], { default: true }),

ignoreDiagnostics: split(process.env['TS_NODE_IGNORE_DIAGNOSTICS']),
typeCheck: yn(process.env['TS_NODE_TYPE_CHECK'])
typeCheck: yn(process.env['TS_NODE_TYPE_CHECK']),
transpileOnly: yn(process.env['TS_NODE_TRANSPILE_ONLY'])
};
/**
* Default TypeScript compiler options required by `ts-node`.
*/
var DEFAULT_COMPILER_OPTIONS = {

@@ -57,2 +67,5 @@ sourceMap: true,

};
/**
* Split a string array of values.
*/
function split(value) {

@@ -62,2 +75,5 @@ return typeof value === 'string' ? value.split(/ *, */g) : undefined;

exports.split = split;
/**
* Parse a string as JSON.
*/
function parse(value) {

@@ -67,2 +83,5 @@ return typeof value === 'string' ? JSON.parse(value) : undefined;

exports.parse = parse;
/**
* Replace backslashes with forward slashes.
*/
function normalizeSlashes(value) {

@@ -72,3 +91,6 @@ return value.replace(/\\/g, '/');

exports.normalizeSlashes = normalizeSlashes;
var TSError = (function (_super) {
/**
* TypeScript diagnostics error.
*/
var TSError = /** @class */ (function (_super) {
__extends(TSError, _super);

@@ -84,2 +106,5 @@ function TSError(diagnostics) {

exports.TSError = TSError;
/**
* Return a default temp directory based on home directory of user.
*/
function getTmpDir() {

@@ -89,2 +114,5 @@ var hash = crypto.createHash('sha256').update(os_1.homedir(), 'utf8').digest('hex');

}
/**
* Register TypeScript compiler.
*/
function register(opts) {

@@ -98,3 +126,3 @@ if (opts === void 0) { opts = {}; }

18002,
18003
18003 // "No inputs were found in config file."
]).map(Number);

@@ -107,2 +135,3 @@ var memoryCache = {

var ignore = options.skipIgnore ? [] : arrify(options.ignore || '/node_modules/').map(function (str) { return new RegExp(str); });
// Install source map support and read from memory cache.
sourceMapSupport.install({

@@ -114,5 +143,6 @@ environment: 'node',

});
// Require the TypeScript compiler and configuration.
var cwd = process.cwd();
var compiler = options.compiler || 'typescript';
var typeCheck = options.typeCheck || false;
var typeCheck = options.typeCheck === true || options.transpileOnly !== true;
var ts = require(compiler);

@@ -126,5 +156,7 @@ var transformers = options.transformers || undefined;

var cachedir = path_1.join(path_1.resolve(cwd, cacheDirectory), getCompilerDigest({ version: ts.version, typeCheck: typeCheck, ignoreDiagnostics: ignoreDiagnostics, config: config, compiler: compiler }));
// Render the configuration errors and exit the script.
if (configDiagnostics.length) {
throw new TSError(formatDiagnostics(configDiagnostics, cwd, ts, 0));
}
// Enable `allowJs` when flag is set.
if (config.options.allowJs) {

@@ -134,2 +166,3 @@ extensions.push('.js');

}
// Add all files into the file hash.
for (var _i = 0, _a = config.fileNames; _i < _a.length; _i++) {

@@ -139,5 +172,11 @@ var fileName = _a[_i];

}
/**
* Get the extension for a transpiled file.
*/
var getExtension = config.options.jsx === ts.JsxEmit.Preserve ?
(function (path) { return /\.[tj]sx$/.test(path) ? '.jsx' : '.js'; }) :
(function (_) { return '.js'; });
/**
* Create the basic required function using transpile mode.
*/
var getOutput = function (code, fileName, lineOffset) {

@@ -162,3 +201,5 @@ if (lineOffset === void 0) { lineOffset = 0; }

};
// Use full language services when the fast option is disabled.
if (typeCheck) {
// Set the file contents into cache.
var updateMemoryCache_1 = function (code, fileName) {

@@ -170,2 +211,3 @@ if (memoryCache.contents[fileName] !== code) {

};
// Create the compiler host for type checking.
var serviceHost = {

@@ -175,2 +217,7 @@ getScriptFileNames: function () { return Object.keys(memoryCache.versions); },

var version = memoryCache.versions[fileName];
// We need to return `undefined` and not a string here because TypeScript will use
// `getScriptVersion` and compare against their own version - which can be `undefined`.
// If we don't return `undefined` it results in `undefined === "undefined"` and run
// `createProgram` again (which is very slow). Using a `string` assertion here to avoid
// TypeScript errors from the function signature (expects `(x: string) => string`).
return version === undefined ? undefined : String(version);

@@ -201,4 +248,6 @@ },

if (lineOffset === void 0) { lineOffset = 0; }
// Must set memory cache before attempting to read file.
updateMemoryCache_1(code, fileName);
var output = service_1.getEmitOutput(fileName);
// Get the relevant diagnostics - this is 3x faster than `getPreEmitDiagnostics`.
var diagnostics = service_1.getCompilerOptionsDiagnostics()

@@ -214,2 +263,3 @@ .concat(service_1.getSyntacticDiagnostics(fileName))

}
// Throw an error when requiring `.d.ts` files.
if (output.outputFiles.length === 0) {

@@ -234,2 +284,3 @@ throw new TypeError('Unable to require `.d.ts` file.\n' +

var register = { cwd: cwd, compile: compile, getTypeInfo: getTypeInfo, extensions: extensions, cachedir: cachedir, ts: ts };
// Register the extensions.
extensions.forEach(function (extension) {

@@ -241,2 +292,5 @@ registerExtension(extension, ignore, register, originalJsHandler);

exports.register = register;
/**
* Check if the filename should be ignored.
*/
function shouldIgnore(filename, ignore) {

@@ -246,2 +300,5 @@ var relname = normalizeSlashes(filename);

}
/**
* Register the extension for node.
*/
function registerExtension(ext, ignore, register, originalHandler) {

@@ -261,9 +318,15 @@ var old = require.extensions[ext] || originalHandler;

}
/**
* Do post-processing on config options to support `ts-node`.
*/
function fixConfig(ts, config) {
// Delete options that *should not* be passed through.
delete config.options.out;
delete config.options.outFile;
delete config.options.declarationDir;
// Target ES5 output by default (instead of ES3).
if (config.options.target === undefined) {
config.options.target = ts.ScriptTarget.ES5;
}
// Target CommonJS modules by default (instead of magically switching to ES6 when the target is ES6).
if (config.options.module === undefined) {

@@ -274,2 +337,5 @@ config.options.module = ts.ModuleKind.CommonJS;

}
/**
* Load TypeScript configuration.
*/
function readConfig(cwd, ts, compilerOptions, fileExists, readFile, project, noProject) {

@@ -279,2 +345,3 @@ var config = { compilerOptions: {} };

var configFileName = undefined;
// Read project configuration when available.
if (!noProject) {

@@ -291,5 +358,9 @@ configFileName = project ? path_1.resolve(cwd, project) : ts.findConfigFile(cwd, fileExists);

}
// Override default configuration options `ts-node` requires.
config.compilerOptions = Object.assign({}, config.compilerOptions, compilerOptions, DEFAULT_COMPILER_OPTIONS);
return fixConfig(ts, ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName));
}
/**
* Wrap the function with caching.
*/
function readThrough(cachedir, shouldCache, memoryCache, compile, getExtension) {

@@ -305,2 +376,3 @@ if (shouldCache === false) {

}
// Make sure the cache directory exists before continuing.
mkdirp.sync(cachedir);

@@ -319,3 +391,3 @@ return function (code, fileName, lineOffset) {

}
catch (err) { }
catch (err) { /* Ignore. */ }
var _a = compile(code, fileName, lineOffset), value = _a[0], sourceMap = _a[1];

@@ -328,2 +400,5 @@ var output = updateOutput(value, fileName, sourceMap, getExtension);

}
/**
* Update the output remapping the source map.
*/
function updateOutput(outputText, fileName, sourceMap, getExtension) {

@@ -335,2 +410,5 @@ var base64Map = new Buffer(updateSourceMap(sourceMap, fileName), 'utf8').toString('base64');

}
/**
* Update the source map contents for improved output.
*/
function updateSourceMap(sourceMapText, fileName) {

@@ -343,18 +421,34 @@ var sourceMap = JSON.parse(sourceMapText);

}
/**
* Get the file name for the cache entry.
*/
function getCacheName(sourceCode, fileName) {
return crypto.createHash('sha256')
.update(path_1.extname(fileName), 'utf8')
.update('\x001\x00', 'utf8')
.update('\x001\x00', 'utf8') // Store "cache version" in hash.
.update(sourceCode, 'utf8')
.digest('hex');
}
/**
* Ensure the given cached content is valid by sniffing for a base64 encoded '}'
* at the end of the content, which should exist if there is a valid sourceMap present.
*/
function isValidCacheContent(contents) {
return /(?:9|0=|Q==)$/.test(contents.slice(-3));
}
/**
* Create a hash of the current configuration.
*/
function getCompilerDigest(obj) {
return crypto.createHash('sha256').update(JSON.stringify(obj), 'utf8').digest('hex');
}
/**
* Filter diagnostics.
*/
function filterDiagnostics(diagnostics, ignore) {
return diagnostics.filter(function (x) { return ignore.indexOf(x.code) === -1; });
}
/**
* Format an array of diagnostics.
*/
function formatDiagnostics(diagnostics, cwd, ts, lineOffset) {

@@ -364,2 +458,5 @@ return diagnostics.map(function (x) { return formatDiagnostic(x, cwd, ts, lineOffset); });

exports.formatDiagnostics = formatDiagnostics;
/**
* Format a diagnostic object into a string.
*/
function formatDiagnostic(diagnostic, cwd, ts, lineOffset) {

@@ -380,2 +477,5 @@ var messageText = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n');

exports.formatDiagnostic = formatDiagnostic;
/**
* Stringify the `TSError` instance.
*/
function printError(error) {

@@ -382,0 +482,0 @@ var title = chalk_1.default.red('⨯') + " Unable to compile TypeScript";

16

dist/index.spec.js

@@ -83,7 +83,9 @@ "use strict";

it('should throw errors', function (done) {
child_process_1.exec(BIN_EXEC + " --typeCheck -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
child_process_1.exec(BIN_EXEC + " -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
if (err === null) {
return done('Command was expected to fail, but it succeeded.');
}
chai_1.expect(err.message).to.match(new RegExp('\\[eval\\]\\.ts \\(1,59\\): Argument of type \'(?:number|123)\' ' +
chai_1.expect(err.message).to.match(new RegExp(
// Node 0.10 can not override the `lineOffset` option.
'\\[eval\\]\\.ts \\(1,59\\): Argument of type \'(?:number|123)\' ' +
'is not assignable to parameter of type \'string\'\\. \\(2345\\)'));

@@ -94,3 +96,3 @@ return done();

it('should be able to ignore diagnostic', function (done) {
child_process_1.exec(BIN_EXEC + " --type-check --ignoreDiagnostics 2345 -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
child_process_1.exec(BIN_EXEC + " --ignoreDiagnostics 2345 -e \"import * as m from './tests/module';console.log(m.example(123))\"", function (err) {
if (err === null) {

@@ -104,3 +106,3 @@ return done('Command was expected to fail, but it succeeded.');

it('should work with source maps', function (done) {
child_process_1.exec(BIN_EXEC + " --type-check tests/throw", function (err) {
child_process_1.exec(BIN_EXEC + " tests/throw", function (err) {
if (err === null) {

@@ -119,3 +121,3 @@ return done('Command was expected to fail, but it succeeded.');

it.skip('eval should work with source maps', function (done) {
child_process_1.exec(BIN_EXEC + " --type-check -p \"import './tests/throw'\"", function (err) {
child_process_1.exec(BIN_EXEC + " -p \"import './tests/throw'\"", function (err) {
if (err === null) {

@@ -132,4 +134,4 @@ return done('Command was expected to fail, but it succeeded.');

});
it('should use transpile mode by default', function (done) {
child_process_1.exec(BIN_EXEC + " -p \"x\"", function (err) {
it('should support transpile only mode', function (done) {
child_process_1.exec(BIN_EXEC + " --transpileOnly -p \"x\"", function (err) {
if (err === null) {

@@ -136,0 +138,0 @@ return done('Command was expected to fail, but it succeeded.');

{
"name": "ts-node",
"version": "5.0.1",
"version": "6.0.0",
"description": "TypeScript execution environment and REPL for node",

@@ -56,3 +56,3 @@ "main": "dist/index.js",

"@types/mkdirp": "^0.5.0",
"@types/mocha": "^2.2.42",
"@types/mocha": "^5.0.0",
"@types/node": "^9.4.6",

@@ -68,3 +68,3 @@ "@types/proxyquire": "^1.3.28",

"ntypescript": "^1.201507091536.1",
"proxyquire": "^1.7.2",
"proxyquire": "^2.0.0",
"react": "^16.0.0",

@@ -71,0 +71,0 @@ "rimraf": "^2.5.4",

@@ -8,3 +8,3 @@ # TypeScript Node

> TypeScript execution environment and REPL for node. **Works with `typescript@>=2.0`**.
> TypeScript execution and REPL for node. **Works with `typescript@>=2.0`**.

@@ -15,4 +15,2 @@ ## Installation

npm install -g ts-node
# Install a TypeScript compiler (requires `typescript` by default).
npm install -g typescript

@@ -27,3 +25,3 @@ ```

* Source map support
* Loads compiler options and `.d.ts` files from `tsconfig.json`
* Loads compiler options from `tsconfig.json`

@@ -33,6 +31,6 @@ ## Usage

```sh
# Execute a script as you would normally with `node`.
# Execute a script as `node` + `tsc`.
ts-node script.ts
# Starts the TypeScript REPL.
# Starts a TypeScript REPL.
ts-node

@@ -54,3 +52,3 @@

You can require `ts-node` and register the loader for future requires by using `require('ts-node').register({ /* options */ })`. You can also use the shortcuts `node -r ts-node/register` or `node -r ts-node/register/type-check` depending on your preferences.
You can require `ts-node` and register the loader for future requires by using `require('ts-node').register({ /* options */ })`. You can also use file shortcuts - `node -r ts-node/register` or `node -r ts-node/register/transpile-only` - depending on your preferences.

@@ -80,5 +78,24 @@ **Note:** If you need to use advanced node.js CLI arguments (e.g. `--inspect`), use them with `node -r ts-node/register` instead of the `ts-node` CLI.

### Visual Studio Code
Create a new node.js 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`).
```json
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"runtimeArgs": [
"-r",
"ts-node/register"
],
"args": [
"${workspaceFolder}/index.ts"
]
}
```
## How It Works
**TypeScript Node** works by registering the TypeScript compiler for the `.ts`, `.tsx` and, with `allowJs` enabled, `.js` extensions. When node.js has a file extension registered (the `require.extensions` object), it will use the extension internally for module resolution. When an extension is unknown to node.js, it will handle the file as `.js` (JavaScript).
**TypeScript Node** works by registering the TypeScript compiler for `.tsx?` and `.jsx?` extension (when `allowJs == true`). When node.js has an extension registered (via `require.extensions`), it will use the extension internally for module resolution. When an extension is unknown to node.js, it handles the file as `.js` (JavaScript).

@@ -112,3 +129,3 @@ **P.S.** This means if you don't register an extension, it is compiled as JavaScript. When `ts-node` is used with `allowJs`, JavaScript files are transpiled using the TypeScript compiler.

* `--typeCheck` Enable type checking for TypeScript (`TS_NODE_TYPE_CHECK`)
* `--transpileOnly` Use TypeScript's faster `transpileModule` (`TS_NODE_TRANSPILE_ONLY`)
* `--cacheDirectory` Configure the output file cache directory (`TS_NODE_CACHE_DIRECTORY`)

@@ -130,2 +147,8 @@ * `-I, --ignore [pattern]` Override the path patterns to skip compilation (`TS_NODE_IGNORE`)

## Watching and Restarting
**TypeScript Node** compiles source code via `require()`, 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](https://github.com/remy/nodemon), [onchange](https://github.com/Qard/onchange) and [node-dev](https://github.com/fgnass/node-dev) work.
There's also [`ts-node-dev`](https://github.com/whitecolor/ts-node-dev), a modified version of [`node-dev`](https://github.com/fgnass/node-dev) using `ts-node` for compilation and won't restart the process on file change.
## License

@@ -132,0 +155,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc