Step-by-step to turn your fresh node project to use typescript

teerasej

Teerasej Jiraphatchandej

Posted on April 26, 2022

Step-by-step to turn your fresh node project to use typescript

OK, you fall in love with typescript, and now you really want to use it in your new express project.

A common approach in using typescript in node project

Start the new node project by running this command in your directory via the terminal.

1. Create a new node project, with a package.json file

npm init
Enter fullscreen mode Exit fullscreen mode

This will generate a new package.json file. Let me show mine:

{
  "name": "friend-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Teerasej Jiraphatchandej",
  "license": "ISC"
}
Enter fullscreen mode Exit fullscreen mode

2. Add packages for typescript

So we want to set up this project for us to use typescript in development. We add 2 packages as devDependencies:

npm i -D @types/node
npm i -D typescript
Enter fullscreen mode Exit fullscreen mode

Here we go. We have package.json file similar to the one below:

{
  "name": "friend-api",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Teerasej Jiraphatchandej",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^17.0.29",
    "typescript": "^4.6.3"
  },
}
Enter fullscreen mode Exit fullscreen mode

3. Add tsconfig.json

OK, let's create another file: tsconfig.json at the root of the project's directory. This file will tell how would typescript's compiler work:

{
    "compilerOptions": {
      "module": "commonjs",
      "esModuleInterop": true,
      "target": "es6",
      "moduleResolution": "node",
      "sourceMap": true,
      "outDir": "dist"
    },
    "lib": ["es2015"]
}
Enter fullscreen mode Exit fullscreen mode

5. Let compile and run

from this point, you can use the following command in the terminal to compile all tsc files in project into /dist directory (as you set it up in tsconfig.json: outDir)

tsc
Enter fullscreen mode Exit fullscreen mode

and you can run your compiled code with

node dist/<file name>.js
Enter fullscreen mode Exit fullscreen mode

6. Done, but you can add more ease

Execute 2 commands repeatedly will take out our energy. You can use the script section in package.json to create a shortcut

{
  ...
  "scripts": {
    "start": "tsc && node dist/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

After save the package.json file, you can compile and run your project with one simple command:

npm run start
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
teerasej
Teerasej Jiraphatchandej

Posted on April 26, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related