DEV Community

ADEKOLA Abdwahab
ADEKOLA Abdwahab

Posted on

How to automatically compile Typescript files to Javascript files and run the Nodejs server automatically

When I started using typescript one of the first challenges I encountered was that I have to build/compile my typescript file to javascript before I can run the node server.

So to compile I would run:

npm run build

and to run the node server, I would issue:

node index.js

To do things automatically I knew I can watch changes to my .js server files by using packages like nodemon, so I installed it, and then set the scripts object like following in my package.json file:

  "scripts": {
    "build": "tsc -p .",
    "start": "node index.js",
    "dev": "nodemon index.ts"

The build property-value is what would be run when we issue npm run build.

The start property-value is what would be run when we issue npm run start. You can answer for the dev, right.

Now to automatically build your typescripts to javascript whenever you make and save changes to a typescript file, there are two ways to go about it

  1. add -w flag to the build script.
  2. or uncomment and then set the watch property to true in the compilerOptions object in your tsconfig.json file.

using the the watch flag -w

Either of these two would keep watching for saved changes in your typescript files and thereby compile automatically.

setting watch to true

So in one terminal run: npm run build, then open another terminal and run npm run dev.

If you issued npm run dev, your server would run and depend on the file name attached in the dev scripts. Conversely for npm run start. In the case here, the server would be running from index.ts if I issued npm run dev.

Compilation from typescripts to javascripts would happen automatically because of the watch flag, -w or setting it to true in the tsconfig.json file.

Server would restart automatically because we are using nodemon to handle it.

Just different terminals.

Also take these tips into consideration:

  1. Nodejs server runs on javascript files
  2. Changes to typescript has be saved and compiled/build to javascript
  3. We need to build automatically
  4. and we need to start our server automatically

Your brother in copy and paste,


Tweet at me @wahabind

Top comments (2)

mrsonj profile image

thank you

Sloan, the sloth mascot
Comment deleted