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
- add -w flag to the build script.
- or uncomment and then set the watch property to true in the compilerOptions object in your tsconfig.json file.
Either of these two would keep watching for saved changes in your typescript files and thereby compile automatically.
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:
- Nodejs server runs on javascript files
- Changes to typescript has be saved and compiled/build to javascript
- We need to build automatically
- and we need to start our server automatically
Your brother in copy and paste,
Abdwahab
Tweet at me @wahabind
Top comments (2)
thank you