DEV Community

Rajat Srivastava
Rajat Srivastava

Posted on • Updated on

Create a new node js project in typescript (for beginners)

I used to work on traditional plain javascript code while working on node js. It caused a lot of problems as

  1. Forget how to use the methods, classes or objects that we built into a module long time ago
  2. When a project becomes larger, bugs mostly comes from a minor mistake which typescript helps eliminating

So, I learned how to setup typescript project from scratch

Create a node project using npm

PROJECT_NAME = <project name>
mkdir $PROJECT_NAME && cd $PROJECT_NAME
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install typescript dependencies

npm i --save-dev typescript ts-node nodemon
Enter fullscreen mode Exit fullscreen mode
  • typescript is for typescript language itself and compiling tool
  • ts-node is used to run typescript without compiling
  • nodemon is used to run/restart node automatically when files changed

Initialize tsconfig.json

npx tsc --init
Enter fullscreen mode Exit fullscreen mode

This creates a tsconfig.json in your project folder. This controls the strictness/settings in typescript files

Adjust tsconfig [optional]

Some basic settings in tsconfig.json that are recommended are

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "declaration": true,
    "sourceMap": true,
    "outDir": "dist",
    "rootDir": "./",
    "strict": true,
    "esModuleInterop": true
  }
}
Enter fullscreen mode Exit fullscreen mode
  • setting target as es6 helps to support es6 code
  • setting declaration true generates corresponding '.d.ts' file
  • setting sourceMap true generates corresponding '.map' file
  • outDir redirects output structure to the directory
  • rootDir specifies the root directory of input files
  • setting strict true enables all strict type-checking options

Add program for testing

echo "console.log('Hello typescript !')" > index.ts
Enter fullscreen mode Exit fullscreen mode

Add scripts to package.json

{
  "main": "dist/index.js",
  "types": "dist/index.d.ts",
  "scripts": {
    "start": "ts-node index.ts",
    "build": "tsc"
  },
}
Enter fullscreen mode Exit fullscreen mode
  • execute npm run start to start application without compile
  • execute npm run build then node dist/index.js to compile and run applcation as javascript

Top comments (1)

Collapse
 
francisco profile image
Francisco M. Delgado

I like how your article is straight to the point. and you let us know what each dependency does in a single sentence. Good stuff!!