TypeScript Setup With Node And Express

Introduction

 
In this article, we'll learn how to handle node & express in Typescript.
 

About Node.js

 
Node.js is an open-source, cross-platform run-time environment used for developing fast and scalable real-time applications with a persistent connection between the user's browser and server. It executes server-side JavaScript code. 
 

About Express.js

 
Express.js is simply a web application framework of Node.js. It helps in developing node-based web applications rapidly. Let's see some of the core features of Ethe xpress framework,
  • Used in hybrid, single and multi-page web application development.
  • Allows  usto setup middle wares to respond to HTTP requests.
  • Helps in rendering dynamic HTML pages by passing arguments to templates.
  • Defines a routing table to perform different actions based on HTTP method and URL.

Typescript

 
TypeScript is a language for application-scale Javascript and can be considered as a superset of JavaScript. It adds optional types to Javascript that support large scale JS applications, on any browser and OS. It can be thought of as JavaScript with additional features such as strong static typing, compilation and object-oriented programming etc.
 
Steps to follow.
 
Let's start the setup for TypeScript with Node and Express.
 
Step 1 - Folder creation and Dependency Installation
 
Create a new folder for our project (after Node and Npm installation):
 
Nodets_express
 
Install the dependencies using NPM
 
npm install typescript
tsc –init
 
TypeScript Setup With Node And Express
 
Step 2 - Configuring TypeScript
  • After the installation, a few configurations have to be done for changing JS to TS.
  • In the tsconfig.json file, modify the below configs.
"target": "es5" -> "target": "es6",
"outDir": "./build",
"rootDir": "./src",
"moduleResolution": "node",
 
Note
The tsconfig.json file is located at the root directory of any TypeScript project. The tsconfig.json file has the details of the root files and the compiler options required to compile the project.
 
TypeScript Setup With Node And Express
 
Step 3
 
Initialize it as an Npm project
 
npm init --y
 
TypeScript Setup With Node And Express
 
Step 4
 
To install the Express framework, use the below commands.
 
npm install express
npm i -D typescript ts-node nodemon @types/node @types/express
 
 
To start with the TS application, create a folder structure as below:
 
src/app.ts
 
 src folder - In the root of our project directory.
 app.ts file - Inside src folder.
 
 In the terminal, execute the below command:
 
cd src
touch app.ts
 
At this point, we should have a folder structure that looks like this,
 
TypeScript Setup With Node And Express
 
TypeScript Setup With Node And Express
 
Now, go to the localhost in the browser. The below result appears which indicates successful execution.
 
TypeScript Setup With Node And Express