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.

Executing TypeScript code involves two steps:

  • Compiling TypeScript to a JavaScript file.
  • Executing the JavaScript file using the Node command.

Node projects utilize a package.json file that contains a scripts section to execute npm scripts.

Let’s see an example of running TypeScript code.

Execute Typescript code using the npm command

There are multiple ways to execute TypeScript code:

  • Plain compilation and execution of TypeScript code

First, create a Node.js project using the npm init command as shown 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

After initializing your project, create an src folder and write a simple “Hello, World!” TypeScript program in src/helloworld.ts:

console.log("Hello World");

Now, add the following scripts to the package.json file

For Windows and Linux environments:

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

In Mac machines,

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

Here, tsc is the TypeScript compiler that converts TypeScript to JavaScript, and node is the Node.js command used to run a JavaScript file.

The pipe symbol (|) executes commands sequentially.

A:\nodejs>npm run start

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

Hello World

This will compile the TypeScript code into JavaScript and then execute it:

This demonstrates how to compile and run TypeScript code using the npm command.