Skip to content

Setup node with typescript (with support to nodemon)

Posted on:July 16, 2023 at 07:00 AM

Initialize npm and install typescript and node types

npm init -y

This will intialize npm with “yes” to all default prompts.

npm install -D typescript @types/node

Typescript and corresponding types for node is installed as dev dependecy, since its not required in production.

Configure package.json

{
  "type": "module",
  "scripts": {
    "build": "tsc"
  }
}

This will enable ES6 modules format. ‘tsc’ is the command to run typescript compiler.

Create and configure TS config

Create a tsconfig.json file in the root of the directory and add the corresponding code

{
  "compilerOptions": {
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "target": "ES2020",
    "sourceMap": true,
    "outDir": "dist"
  },
  "include": ["src/**/*"]
}

The source directory is src and destination directory is dist. You can change this if you want.

Seting up nodemon and ts-node

npm install -D ts-node nodemon

Change package.json

"scripts": {
    "build": "tsc",
    "dev": "nodemon src/server.ts"
  },

Run the code

Use npm run dev for development and npm run build for production ready code.

Voila!! Now you can create strong typesafe node js applications.