What is ts-node and why is it needed?
ts-node is a TypeScript engine for Node.js that allows you to run TypeScript files directly, without prior compilation to JavaScript. It works as a REPL (Read-Eval-Print Loop) and as a command-line tool, providing seamless integration of TypeScript into the Node.js ecosystem.
Main use cases:
- Fast development and prototyping — no need to wait for compilation on every change
- Running scripts — executing TypeScript files in production (with caution)
- Testing — running tests written in TypeScript
- Interactive development — REPL mode for experimenting with TypeScript
- Project migration — gradual transition from JavaScript to TypeScript
Unlike the standard approach (compilation via tsc and running via node), ts-node makes the development process smoother and faster.
Installing ts-node
Installation is done via npm (Node.js package manager). For Python developers: this is analogous to pip install.
# Global installation (available everywhere)npm install -g ts-node
# Local installation (recommended for projects)npm install --save-dev ts-node
# Installation together with TypeScript (if not already installed)npm install --save-dev ts-node typescript
# For working with specific TypeScript versionsnpm install --save-dev ts-node@10.9.2 typescript@5.3.3After installation, check the version:
ts-node --version# Output: v10.9.2Quick start with a code example
Create a file hello.ts:
// hello.tsinterface Greeting { name: string; age: number;}
function greet(person: Greeting): string { return `Hello, ${person.name}! You are ${person.age} years old.`;}
const user: Greeting = { name: "Alexey", age: 30 };console.log(greet(user));Run without compilation:
ts-node hello.ts# Output: Hello, Alexey! You are 30 years old.For comparison, the usual method would take two steps:
tsc hello.ts # compilation to hello.jsnode hello.js # running the compiled fileMain methods and functions of ts-node
1. ts-node [file.ts] — Basic file execution
Description: The main command for executing a TypeScript file. ts-node automatically compiles and runs the code.
Parameters:
file.ts— path to the TypeScript file--projector-P— path to tsconfig.json--transpile-only— transpilation only (faster, but without type checking)
Example:
# Normal executionts-node app.ts
# With configuration specifiedts-node --project tsconfig.prod.json app.ts
# Transpile only (faster)ts-node --transpile-only app.ts2. ts-node --eval — Execute code from a string
Description: Allows you to execute TypeScript code passed as a string, without creating a file.
Parameters:
-eor--eval— string with TypeScript code-por--print— print the execution result
Example:
# Simple expressionts-node -e "console.log('Hello from ts-node!')"
# Using TypeScript featurests-node -e "interface User { name: string }const user: User = { name: 'Maria' };console.log(user.name);"
# With result outputts-node -p "1 + 2"