· hands on

Fastest way to set up a TypeScript project with Node.js (npm)

Setting up a TypeScript project with Node.js is quick and easy. Here are the steps…

Setting up a TypeScript project with Node.js takes only a few minutes. Here is how to do it the fastest way by just using npm and yarn.

Contents

Tutorial

TL;DR

  1. npm init -y
  2. yarn add -DE typescript
  3. npx tsc --init
  4. echo console.log('Hello from TypeScript'); > index.ts
  5. npx tsc
  6. node index.js

Tested with TypeScript v3.9.7, Node.js v13.10.1 & yarn v1.21.1.

Prerequisites

To setup a Node.js project with TypeScript from scratch we have to install Node.js and preferably a package manager like Yarn (npm works too).

Creating a Node.js package

The Node Package Manager (npm) ships with Node.js and supplies a wizard to create new packages using the initializer command npm init. To prevent the wizard from asking questions we can run it using the -y flag which will answer all setup questions with "yes".

Adding TypeScript

Once our Node package is initialized, we can add dependencies using npm install or yarn add. To start a TypeScript project we need to install/add typescript.

Setting up TypeScript

To start a TypeScript project it is best to create a compiler configuration. This can be done with tsc --init, which will create a basic project setup using documented compiler options.

Writing TypeScript code

A good entry point for our application is a index.ts file where we will save our TypeScript code. To keep things simple, we will write a small program that just outputs a message:

index.ts
console.log('Hello from TypeScript');

Compiling TypeScript code

Node.js is a JavaScript runtime and does not, unlike Deno, execute TypeScript code by default. That's why we have to transpile our TypeScript code to JavaScript. This code conversion can be done by simply executing the TypeScript compiler with the tsc command. As a result we will receive a new file called index.js.

Running TypeScript code

The transpiled index.js file can be run with node index.js and will display our message on the command prompt.

Back to Blog