Happylab Logo
Published on

Day03: TypeScript Made Easy with Automatic Compilation Using tsc + nodemon

Authors

Day03: TypeScript Made Easy with Automatic Compilation Using tsc + nodemon


In the previous article, I mentioned that we have to manually run tsc xx.ts and node xx.js every time we write. Isn't that tiring? I'm tired, so I'm sharing this article to help us automate compilation and speed up our learning time.

  1. Create two folders: src and dist.

  2. In the src folder, create a file named index.ts and write:

const index: string = "this's index"
console.log(index)
  1. The folder structure will look like this:
project

└───dist
│   │
└───src
    │   index.ts
  1. Initialize the project in the folder by running the npm initialization command:
npm init -y
  1. Run the following command to generate the tsconfig.json file, which is the TS initialization configuration file:
tsc --init
  1. Open tsconfig.json and set the paths for outDir and rootDir.
"outDir": "./dist", // Path where the compiled JS files will be generated
"rootDir": "./src",   // Path representing the entry point for TS files
  1. Run tsc, and you will see the compiled index.js in the dist folder.
tsc
  1. Run the following command to install nodemon and concurrently:
npm i nodemon concurrently --save-dev
  1. Modify the scripts section in package.json:
  "scripts": {
    "start:build": "tsc -w",  // Watch TS files in src and automatically compile JS files
    "start:run": "nodemon ./dist/index.js", // Execute when a new JS file is generated
    "start": "concurrently npm:start:*" // Execute all commands containing "start" (including start:build and start:run)
  },
  1. Run:
npm start
  1. At this point, you should see the compiled JS file in the dist folder, and the terminal should print this's index, indicating successful execution.
project
│   node_modules
package-lock.json
package.json
│   tsconfig.json
└───dist
│   │   index.js
└───src
    │   index.ts

![](https://i.imgur.com/uwn998F.png =500x)

Isn't it convenient? You can check the demo here, which I have also synchronized on GitHub.


In this article, we set the outDir and rootDir in tsconfig.json. In the next article, I will note what other settings can be configured in tsconfig.json. I initially found it confusing when I saw the handbook introducing types, so I decided to move this topic up for better understanding later.


References

https://www.typescripttutorial.net/typescript-tutorial/nodejs-typescript/