ts-node
- Version 10.9.2
- Published
- 757 kB
- 13 dependencies
- MIT license
Install
npm i ts-node
yarn add ts-node
pnpm add ts-node
Overview
TypeScript execution environment and REPL for node.js, with source map support
Index
Variables
Functions
Classes
Interfaces
CreateOptions
- compiler
- compilerHost
- compilerOptions
- cwd
- dir
- emit
- esm
- experimentalReplAwait
- experimentalSpecifierResolution
- experimentalTsImportSpecifiers
- fileExists
- files
- ignore
- ignoreDiagnostics
- logError
- moduleTypes
- preferTsExts
- pretty
- project
- projectSearchDir
- readFile
- require
- scope
- scopeDir
- skipIgnore
- skipProject
- swc
- transformers
- transpileOnly
- transpiler
- tsTrace
- typeCheck
TSCommon
- createDocumentRegistry
- createEmitAndSemanticDiagnosticsBuilderProgram
- createIncrementalCompilerHost
- createIncrementalProgram
- createLanguageService
- createModuleResolutionCache
- createSourceFile
- displayPartsToString
- Extension
- findConfigFile
- flattenDiagnosticMessageText
- formatDiagnostics
- formatDiagnosticsWithColorAndContext
- getDefaultLibFileName
- getDefaultLibFilePath
- getPreEmitDiagnostics
- JsxEmit
- ModuleKind
- ModuleResolutionKind
- parseJsonConfigFileContent
- readConfigFile
- resolveModuleName
- resolveModuleNameFromCache
- resolveTypeReferenceDirective
- ScriptSnapshot
- ScriptTarget
- sys
- transpileModule
- version
Type Aliases
Namespaces
Variables
variable createEsmHooks
const createEsmHooks: ( tsNodeService: Service) => NodeLoaderHooksAPI1 | NodeLoaderHooksAPI2;
Create an implementation of node's ESM loader hooks.
This may be useful if you want to wrap or compose the loader hooks to add additional functionality or combine with another loader.
Node changed the hooks API, so there are two possible APIs. This function detects your node version and returns the appropriate API.
ESM Loader
variable REGISTER_INSTANCE
const REGISTER_INSTANCE: Symbol;
Registered
ts-node
instance information.
variable VERSION
const VERSION: any;
Export the current version.
Functions
function create
create: (rawOptions?: CreateOptions) => Service;
Create TypeScript compiler instance.
Basic
function createRepl
createRepl: (options?: CreateReplOptions) => ReplService;
Create a ts-node REPL instance.
Pay close attention to the example below. Today, the API requires a few lines of boilerplate to correctly bind the
ReplService
to the ts-nodeService
and vice-versa.Usage example:
const repl = tsNode.createRepl(); const service = tsNode.create({...repl.evalAwarePartialHost}); repl.setService(service); repl.start();
REPL
function register
register: { (opts?: RegisterOptions): Service; (service: Service): Service };
Create a new TypeScript compiler instance and register it onto node.js
Basic
Register TypeScript compiler instance onto node.js
Basic
Classes
class TSError
class TSError extends BaseError {}
TypeScript diagnostics error.
constructor
constructor( diagnosticText: string, diagnosticCodes: number[], diagnostics?: readonly _ts.Diagnostic[]);
property diagnosticCodes
diagnosticCodes: number[];
property diagnostics
diagnostics: readonly _ts.Diagnostic[];
property diagnosticText
diagnosticText: string;
property name
name: string;
Interfaces
interface CreateOptions
interface CreateOptions {}
Options for creating a new TypeScript compiler instance.
Basic
property compiler
compiler?: string;
Specify a custom TypeScript compiler.
"typescript"
property compilerHost
compilerHost?: boolean;
Use TypeScript's compiler host API instead of the language service API.
false
property compilerOptions
compilerOptions?: object;
JSON object to merge with TypeScript
compilerOptions
.[{"$ref": "https://schemastore.azurewebsites.net/schemas/json/tsconfig.json#definitions/compilerOptionsDefinition/properties/compilerOptions"}]
property cwd
cwd?: string;
Behave as if invoked within this working directory. Roughly equivalent to
cd $dir && ts-node ...
process.cwd()
property dir
dir?: string;
Legacy alias for
cwd
Deprecated
use
projectSearchDir
orcwd
property emit
emit?: boolean;
Emit output files into
.ts-node
directory.false
property esm
esm?: boolean;
Enable native ESM support.
For details, see https://typestrong.org/ts-node/docs/imports#native-ecmascript-modules
property experimentalReplAwait
experimentalReplAwait?: boolean;
Allows the usage of top level await in REPL.
Uses node's implementation which accomplishes this with an AST syntax transformation.
Enabled by default when tsconfig target is es2018 or above. Set to false to disable.
**Note**: setting to
true
when tsconfig target is too low will throw an Error. Leave asundefined
to get default, automatic behavior.
property experimentalSpecifierResolution
experimentalSpecifierResolution?: 'node' | 'explicit';
Like node's
--experimental-specifier-resolution
, , but can also be set in yourtsconfig.json
for convenience.For details, see https://nodejs.org/dist/latest-v18.x/docs/api/esm.html#customizing-esm-specifier-resolution-algorithm
property experimentalTsImportSpecifiers
experimentalTsImportSpecifiers?: boolean;
Allow using voluntary
.ts
file extension in import specifiers.Typically, in ESM projects, import specifiers must have an emit extension,
.js
,.cjs
, or.mjs
, and we automatically map to the corresponding.ts
,.cts
, or.mts
source file. This is the recommended approach.However, if you really want to use
.ts
in import specifiers, and are aware that this may break tooling, you can enable this flag.
property fileExists
fileExists?: (path: string) => boolean;
property files
files?: boolean;
Load "files" and "include" from
tsconfig.json
on startup.Default is to override
tsconfig.json
"files" and "include" to only include the entrypoint script.false
property ignore
ignore?: string[];
Paths which should not be compiled.
Each string in the array is converted to a regular expression via
new RegExp()
and tested against source paths prior to compilation.Source paths are normalized to posix-style separators, relative to the directory containing
tsconfig.json
or to cwd if notsconfig.json
is loaded.Default is to ignore all node_modules subdirectories.
["(?:^|/)node_modules/"]
property ignoreDiagnostics
ignoreDiagnostics?: Array<number | string>;
Ignore TypeScript warnings by diagnostic code.
property logError
logError?: boolean;
Logs TypeScript errors to stderr instead of throwing exceptions.
false
property moduleTypes
moduleTypes?: ModuleTypes;
Override certain paths to be compiled and executed as CommonJS or ECMAScript modules. When overridden, the tsconfig "module" and package.json "type" fields are overridden, and the file extension is ignored. This is useful if you cannot use .mts, .cts, .mjs, or .cjs file extensions; it achieves the same effect.
Each key is a glob pattern following the same rules 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
overrides either of the above to default behavior, which obeys package.json "type" and tsconfig.json "module" options.
property preferTsExts
preferTsExts?: boolean;
Re-order file extensions so that TypeScript imports are preferred.
For example, when both
index.js
andindex.ts
exist, enabling this option causesrequire('./index')
to resolve toindex.ts
instead ofindex.js
false
property pretty
pretty?: boolean;
Use pretty diagnostic formatter.
false
property project
project?: string;
Path to TypeScript config file or directory containing a
tsconfig.json
. Similar to thetsc --project
flag: https://www.typescriptlang.org/docs/handbook/compiler-options.html
property projectSearchDir
projectSearchDir?: string;
Search for TypeScript config file (
tsconfig.json
) in this or parent directories.
property readFile
readFile?: (path: string) => string | undefined;
property require
require?: Array<string>;
Modules to require, like node's
--require
flag.If specified in
tsconfig.json
, the modules will be resolved relative to thetsconfig.json
file.If specified programmatically, each input string should be pre-resolved to an absolute path for best results.
property scope
scope?: boolean;
Scope compiler to files within
scopeDir
.false
property scopeDir
scopeDir?: string;
First of:
tsconfig.json
"rootDir" if specified, directory containingtsconfig.json
, or cwd if notsconfig.json
is loaded.
property skipIgnore
skipIgnore?: boolean;
Skip ignore check, so that compilation will be attempted for all files with matching extensions.
false
property skipProject
skipProject?: boolean;
Skip project config resolution and loading.
false
property swc
swc?: boolean;
Transpile with swc instead of the TypeScript compiler, and skip typechecking.
Equivalent to setting both
transpileOnly: true
andtranspiler: 'ts-node/transpilers/swc'
For complete instructions: https://typestrong.org/ts-node/docs/transpilers
property transformers
transformers?: | _ts.CustomTransformers | ((p: _ts.Program) => _ts.CustomTransformers);
property transpileOnly
transpileOnly?: boolean;
Use TypeScript's faster
transpileModule
.false
property transpiler
transpiler?: string | [string, object];
Specify a custom transpiler for use with transpileOnly
property tsTrace
tsTrace?: (str: string) => void;
A function to collect trace messages from the TypeScript compiler, for example when
traceResolution
is enabled.console.log
property typeCheck
typeCheck?: boolean;
**DEPRECATED** Specify type-check is enabled (e.g.
transpileOnly == false
).true
interface CreateReplOptions
interface CreateReplOptions {}
REPL
interface CreateTranspilerOptions
interface CreateTranspilerOptions {}
Transpiler
property service
service: Pick< Service, Extract<'config' | 'options' | 'projectLocalResolveHelper', keyof Service>>;
interface NodeLoaderHooksAPI1
interface NodeLoaderHooksAPI1 {}
property getFormat
getFormat: NodeLoaderHooksAPI1.GetFormatHook;
property resolve
resolve: NodeLoaderHooksAPI1.ResolveHook;
property transformSource
transformSource: NodeLoaderHooksAPI1.TransformSourceHook;
interface NodeLoaderHooksAPI2
interface NodeLoaderHooksAPI2 {}
interface RegisterOptions
interface RegisterOptions extends CreateOptions {}
Options for registering a TypeScript compiler instance globally.
Basic
property experimentalResolver
experimentalResolver?: boolean;
Enable experimental features that re-map imports and require calls to support:
baseUrl
,paths
,rootDirs
,.js
to.ts
file extension mappings,outDir
torootDir
mappings for composite projects and monorepos.For details, see https://github.com/TypeStrong/ts-node/issues/1514
interface ReplService
interface ReplService {}
property evalAwarePartialHost
evalAwarePartialHost: EvalAwarePartialHost;
property state
readonly state: EvalState;
method evalCode
evalCode: (code: string) => any;
Append code to the virtual source file, compile it to JavaScript, throw semantic errors if the typechecker is enabled, and execute it.
Note: typically, you will want to call
start()
instead of using this method.Parameter code
string of TypeScript.
method nodeEval
nodeEval: ( code: string, context: any, _filename: string, callback: (err: Error | null, result?: any) => any) => void;
eval
implementation compatible with node's REPL APICan be used in advanced scenarios if you want to manually create your own node REPL instance and delegate eval to this
ReplService
.Example:
import {start} from 'repl'; const replService: tsNode.ReplService = ...; // assuming you have already created a ts-node ReplService const nodeRepl = start({eval: replService.eval});
method setService
setService: (service: Service) => void;
Bind this REPL to a ts-node compiler service. A compiler service must be bound before
eval
-ing code or starting the REPL
method start
start: { (): void; (code: string): void };
Start a node REPL
Start a node REPL, evaling a string of TypeScript before it starts.
Deprecated
interface Service
interface Service {}
Primary ts-node service, which wraps the TypeScript API and can compile TypeScript to JavaScript
property config
config: _ts.ParsedCommandLine;
property options
options: RegisterOptions;
property ts
ts: TSCommon;
method compile
compile: (code: string, fileName: string, lineOffset?: number) => string;
method enabled
enabled: (enabled?: boolean) => boolean;
method getTypeInfo
getTypeInfo: (code: string, fileName: string, position: number) => TypeInfo;
method ignored
ignored: (fileName: string) => boolean;
interface TranspileOptions
interface TranspileOptions {}
Transpiler
property fileName
fileName: string;
interface TranspileOutput
interface TranspileOutput {}
Transpiler
property diagnostics
diagnostics?: ts.Diagnostic[];
property outputText
outputText: string;
property sourceMapText
sourceMapText?: string;
interface Transpiler
interface Transpiler {}
Transpiler
method transpile
transpile: (input: string, options: TranspileOptions) => TranspileOutput;
interface TranspilerModule
interface TranspilerModule {}
Third-party transpilers are implemented as a CommonJS module with a named export "create"
Transpiler
property create
create: TranspilerFactory;
interface TSCommon
interface TSCommon {}
Common TypeScript interfaces between versions. We endeavour to write ts-node's own code against these types instead of against
import "typescript"
, though we are not yet doing this consistently.Sometimes typescript@next adds an API we need to use. But we build ts-node against typescript@latest. In these cases, we must declare that API explicitly here. Our declarations include the newer typescript@next APIs. Importantly, these re-declarations are *not* TypeScript internals. They are public APIs that only exist in pre-release versions of typescript.
property createDocumentRegistry
createDocumentRegistry: typeof _ts.createDocumentRegistry;
property createEmitAndSemanticDiagnosticsBuilderProgram
createEmitAndSemanticDiagnosticsBuilderProgram: typeof _ts.createEmitAndSemanticDiagnosticsBuilderProgram;
property createIncrementalCompilerHost
createIncrementalCompilerHost: typeof _ts.createIncrementalCompilerHost;
property createIncrementalProgram
createIncrementalProgram: typeof _ts.createIncrementalProgram;
property createLanguageService
createLanguageService: typeof _ts.createLanguageService;
property createModuleResolutionCache
createModuleResolutionCache: typeof _ts.createModuleResolutionCache;
property createSourceFile
createSourceFile: typeof _ts.createSourceFile;
property displayPartsToString
displayPartsToString: typeof _ts.displayPartsToString;
property Extension
Extension: typeof _ts.Extension;
property findConfigFile
findConfigFile: typeof _ts.findConfigFile;
property flattenDiagnosticMessageText
flattenDiagnosticMessageText: typeof _ts.flattenDiagnosticMessageText;
property formatDiagnostics
formatDiagnostics: typeof _ts.formatDiagnostics;
property formatDiagnosticsWithColorAndContext
formatDiagnosticsWithColorAndContext: typeof _ts.formatDiagnosticsWithColorAndContext;
property getDefaultLibFileName
getDefaultLibFileName: typeof _ts.getDefaultLibFileName;
property getDefaultLibFilePath
getDefaultLibFilePath: typeof _ts.getDefaultLibFilePath;
property getPreEmitDiagnostics
getPreEmitDiagnostics: typeof _ts.getPreEmitDiagnostics;
property JsxEmit
JsxEmit: typeof _ts.JsxEmit;
property ModuleKind
ModuleKind: TSCommon.ModuleKindEnum;
property ModuleResolutionKind
ModuleResolutionKind: typeof _ts.ModuleResolutionKind;
property parseJsonConfigFileContent
parseJsonConfigFileContent: typeof _ts.parseJsonConfigFileContent;
property readConfigFile
readConfigFile: typeof _ts.readConfigFile;
property resolveModuleName
resolveModuleName: typeof _ts.resolveModuleName;
property resolveModuleNameFromCache
resolveModuleNameFromCache: typeof _ts.resolveModuleNameFromCache;
property resolveTypeReferenceDirective
resolveTypeReferenceDirective: typeof _ts.resolveTypeReferenceDirective;
property ScriptSnapshot
ScriptSnapshot: typeof _ts.ScriptSnapshot;
property ScriptTarget
ScriptTarget: typeof _ts.ScriptTarget;
property sys
sys: typeof _ts.sys;
property transpileModule
transpileModule: typeof _ts.transpileModule;
property version
version: typeof _ts.version;
interface TsConfigOptions
interface TsConfigOptions extends Omit< RegisterOptions, | 'transformers' | 'readFile' | 'fileExists' | 'skipProject' | 'project' | 'dir' | 'cwd' | 'projectSearchDir' | 'optionBasePaths' | 'tsTrace' > {}
Must be an interface to support
typescript-json-schema
.
Type Aliases
type EvalAwarePartialHost
type EvalAwarePartialHost = Pick<CreateOptions, 'readFile' | 'fileExists'>;
Filesystem host functions which are aware of the "virtual"
[eval].ts
,<repl>
, or[stdin].ts
file used to compile REPL inputs. Must be passed tocreate()
to create a ts-node compiler service which can compile REPL inputs.
type ExperimentalSpecifierResolution
type ExperimentalSpecifierResolution = 'node' | 'explicit';
type ModuleTypeOverride
type ModuleTypeOverride = 'cjs' | 'esm' | 'package';
type ModuleTypes
type ModuleTypes = Record<string, ModuleTypeOverride>;
type NodeLoaderHooksFormat
type NodeLoaderHooksFormat = | 'builtin' | 'commonjs' | 'dynamic' | 'json' | 'module' | 'wasm';
type NodeModuleEmitKind
type NodeModuleEmitKind = 'nodeesm' | 'nodecjs';
When using
module: nodenext
ormodule: node12
, there are two possible styles of emit depending in file extension or package.json "type":- CommonJS with dynamic imports preserved (not transformed into
require()
calls) - ECMAScript modules withimport foo = require()
transformed intorequire = createRequire(); const foo = require()
type Register
type Register = Service;
Re-export of
Service
interface for backwards-compatibilitySee Also
{Service}
Deprecated
use
Service
instead
type TranspilerFactory
type TranspilerFactory = (options: CreateTranspilerOptions) => Transpiler;
Called by ts-node to create a custom transpiler.
Transpiler
Namespaces
namespace global
namespace global {}
Expose
REGISTER_INSTANCE
information on node.jsprocess
.
namespace global.NodeJS
namespace global.NodeJS {}
interface Process
interface Process {}
property [REGISTER_INSTANCE]
[REGISTER_INSTANCE]?: Service;
namespace NodeLoaderHooksAPI1
namespace NodeLoaderHooksAPI1 {}
type GetFormatHook
type GetFormatHook = ( url: string, context: {}, defaultGetFormat: GetFormatHook) => Promise<{ format: NodeLoaderHooksFormat;}>;
type ResolveHook
type ResolveHook = NodeLoaderHooksAPI2.ResolveHook;
type TransformSourceHook
type TransformSourceHook = ( source: string | Buffer, context: { url: string; format: NodeLoaderHooksFormat; }, defaultTransformSource: NodeLoaderHooksAPI1.TransformSourceHook) => Promise<{ source: string | Buffer;}>;
namespace NodeLoaderHooksAPI2
namespace NodeLoaderHooksAPI2 {}
interface NodeImportAssertions
interface NodeImportAssertions {}
property type
type?: 'json';
type LoadHook
type LoadHook = ( url: string, context: { format: NodeLoaderHooksFormat | null | undefined; importAssertions?: NodeImportAssertions; }, defaultLoad: NodeLoaderHooksAPI2['load']) => Promise<{ format: NodeLoaderHooksFormat; source: string | Buffer | undefined; shortCircuit?: boolean;}>;
type NodeImportConditions
type NodeImportConditions = unknown;
type ResolveHook
type ResolveHook = ( specifier: string, context: { conditions?: NodeImportConditions; importAssertions?: NodeImportAssertions; parentURL: string; }, defaultResolve: ResolveHook) => Promise<{ url: string; format?: NodeLoaderHooksFormat; shortCircuit?: boolean;}>;
namespace TSCommon
namespace TSCommon {}
interface LanguageServiceHost
interface LanguageServiceHost extends _ts.LanguageServiceHost {}
type CompilerOptions
type CompilerOptions = _ts.CompilerOptions;
type FileReference
type FileReference = _ts.FileReference;
type ModuleKindEnum
type ModuleKindEnum = typeof _ts.ModuleKind & { Node16: typeof _ts.ModuleKind extends { Node16: any; } ? (typeof _ts.ModuleKind)['Node16'] : 100;};
type ModuleResolutionHost
type ModuleResolutionHost = _ts.ModuleResolutionHost;
type ParsedCommandLine
type ParsedCommandLine = _ts.ParsedCommandLine;
type ResolvedModule
type ResolvedModule = _ts.ResolvedModule;
type ResolvedModuleWithFailedLookupLocations
type ResolvedModuleWithFailedLookupLocations = _ts.ResolvedModuleWithFailedLookupLocations;
type ResolvedProjectReference
type ResolvedProjectReference = _ts.ResolvedProjectReference;
type ResolvedTypeReferenceDirective
type ResolvedTypeReferenceDirective = _ts.ResolvedTypeReferenceDirective;
type SourceFile
type SourceFile = _ts.SourceFile;
namespace TSCommon.ModuleKind
namespace TSCommon.ModuleKind {}
Package Files (5)
Dependencies (13)
Dev Dependencies (31)
- @microsoft/api-extractor
- @swc/core
- @swc/wasm
- @types/diff
- @types/lodash
- @types/node
- @types/proper-lockfile
- @types/proxyquire
- @types/react
- @types/rimraf
- @types/semver
- @yarnpkg/fslib
- ava
- axios
- dprint
- expect
- get-stream
- lodash
- ntypescript
- nyc
- outdent
- proper-lockfile
- proxyquire
- react
- rimraf
- semver
- throat
- typedoc
- typescript
- typescript-json-schema
- util.promisify
Peer Dependencies (4)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/ts-node
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/ts-node)
- HTML<a href="https://www.jsdocs.io/package/ts-node"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 5032 ms. - Missing or incorrect documentation? Open an issue for this package.