How to properly watch Node and TypeScript apps ๐Ÿ‘€

- 1 min

Iโ€™m really liking Node, especially as a prototyping tool. Itโ€™s just incredibly fast to hack something together that kind of works. My preferred language to work with it is TypeScript, because types.

When prototyping itโ€™s very common to do a lot of rebuilding and observing changes - be it for tests, or for a debug build when running an API. Because of that, a lot of tools ship with some kind of watch command that watches your directory for changes, and rebuilds whatever has changed, whenever itโ€™s changed.

Not in my TypeScript/Node setup, though! Well, to be exact - there is a flag to watch on the tsc TypeScript compiler command, and thereโ€™s a tool called nodemon that watches and runs Node apps for you, but they donโ€™t necessarily work nicely together!

What we need is:

  1. tsc to watch our src/ dir for changes, outputing to build/
  2. nodemon to watch our build/ dir for changes and running index.js

In your package.json you can therefore make two entries - watch-build and watch-run, that will run their respective commands:

"scripts": {
  //...
  "watch-build": "tsc --watch",
  "watch-run": "nodemon --watch build build/index.js",
}

Now, this will work fine if we just run each of these commands in different terminal tabs, or windows. Of course, that would require me to have two tabs open, and thatโ€™s absolutely unacceptable!

Thatโ€™s where a bit of shell wizardy comes in handy, especially the process fork operator: &. You can use that to split a process in 2, so they will run in parallel. I created another script entry, linking my two watch-* scripts:

"scripts": {
  //...
  "๐Ÿ‘€": "yarn watch-build & yarn watch-run"
}

Voilรก - running yarn ๐Ÿ‘€ now does what I wanted all along!

Zan Markan

Zan Markan

Space Cowboy, Avocado, Speaker, Immigrant.

comments powered by Disqus
rss facebook twitter github youtube mail spotify lastfm instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora