How to Compile and Run Typescript using npm command

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

It involves two steps to execute typescript code

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

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

Let’s see an example to run typescript code.

Execute Typescript code using the npm command

There are multiple ways we can execute typescript code

  • Plain compile and execute typescript code

First, Create a Nodejs Project using the 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>` afterward 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)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
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 a Nodejs Project with default package.json

Create an src folder and write a simple helloworld typescript program

src/helloworld.ts

console.log("Hello World");

Add the scripts to package.json

In Windows and Linux environments, add the following

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

In Mac machines,

"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 a javascript file

The pipe symbol executes commands in sequential execution.

A:\nodejs>npm run run

> tsapp@1.0.0 run
> tsc src/helloworld.ts | node src/helloworld.js

Hello World