Skip to content
DeveloperMemos

Running TypeScript Files from the Command Line

TypeScript, Node.js, Command Line1 min read

Running TypeScript files from the command line can be a bit different compared to running plain JavaScript files due to the need for compilation. This article guides you through setting up your environment to run TypeScript files directly from the command line.

Prerequisites

  • Node.js installed
  • npm (Node Package Manager)

Step 1: Install TypeScript and ts-node

First, you need to install TypeScript and ts-node. While TypeScript is the primary compiler, ts-node provides the ability to execute TypeScript files directly.

1npm install -g typescript ts-node

This command installs TypeScript and ts-node globally.

Step 2: Creating a TypeScript File

Create a TypeScript file, for example, hello.ts, with the following content:

1console.log('Hello from TypeScript');

Step 3: Running the TypeScript File

Now, you can run the TypeScript file using ts-node:

1ts-node hello.ts

You should see the output: "Hello from TypeScript".

Using npx with ts-node (Optional)

If you prefer not to install packages globally, you can use npx to run ts-node without installing it globally:

1npx ts-node hello.ts

In Closing

Running TypeScript files from the command line is straightforward with ts-node. It allows you to execute TypeScript files directly without the need to compile them into JavaScript first. This setup is particularly useful for development and testing purposes.