How to properly watch Node and TypeScript apps 👀

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!