TypeScript easy setup for Node project


Type script has been #1 choice for developing JavaScript application. It is rich with its features and types. TS is a super set of Java Script.

Programmers first write app in typescript and compiler can covert it to superior vanilla JavaScript.

Node and Typescript

In Nodejs developers can write app with TS which require some basic setup. The following package should be installed before the setup

  • typescript
  • ts-node
  • @types/node
  • nodemon
npm install typescript ts-node @types/node nodemon --save

Generate tsconfig

TypeScript settings for Node can be configured using a file tsconfig.json. As we we generate the package.jos we can create the tsconfig with tsc command

npx tsc --init

The file will come with lots of setting most of them are commented . We need to focus on few settings.

Important settings

   "outDir": "./dist",                  
   "rootDir": "./src",  
   "strict": true,  
   "moduleResolution": "node",  

The above settings should be configured which need to specify the root directory and output directory where we place the converted/compiled JS code.

The file structure we used in dist folder will be same as src except file type will be .js

The package.json scripts

, a sample script will look like this

  "scripts": {
   "start": "node dist/app.js",
   "dev":"nodemon src/app.ts",
   "build": "tsc -p ."
  }

configure your entry point script, it can be a app.js or index.js

Run , Action

Let’s run the script

dev

This script will run the script, not generated the js files yet

yarn dev

build

This will generate the js files in Dist folder and ready to start

yarn build

start

yarn start

This script meant to run the js file from dist folder

You may love to read following Typescript posts

Published by

Manoj

A developer,teacher and a blogger obsessed with Python,Dart and open source world from India

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.