How to Compile and Run Typescript using npm command

Typescript is compiled to javascript during compilation phase. next, you have to execute node command to run javascript file.

It involves two steps to execute typescript code

  • Compiles typescript to javascript file
  • Executes Javascript file using node command.

node projects using package.json that contains scripts section to execute npm scripts.

Let’s see an example to run typescript code.

Execute Typescript code using npm command

There are multiple ways we can execute typescript code

  • Plain compile and execute typescript code

First, Create a Nodejs Project using npm init command as given below

A:\nodejs>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.

See `npm help init` for definitive documentation on these fields
and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (nodejs) tsapp
version: (1.0.0)
entry point: (index.js)
test command:
git repository:
license: (ISC)
About to write to A:\nodejs\package.json:

  "name": "tsapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  "author": "",
  "license": "ISC"

Is this OK? (yes)

This creates an Nodejs Project with default package.json

Create a src folder and write a simple helloworld typescript program


console.log("Hello World");

Add the scripts to package.json

In Windows and Linux environment, add following

"scripts": {
    "start": "tsc src/helloworld.ts | node src/helloworld.js "

In Mac machine,

"scripts": {
    "start": "tsc src/helloworld.ts && node src/helloworld.js "

tsc is a typescript compiler that converts to javascript. node is a node command to run javascript file

Pipe symbol executes commands in sequential execution.

A:\nodejs>npm run run

> [email protected] run
> tsc src/helloworld.ts | node src/helloworld.js

Hello World
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.