How to run multiple watch scripts in parallel

December 05, 2018

The problem

In each project must be a command the start it, usually this command is been store under start script in package.json. Sometimes, this command is combine of multiple sub tasks. For example, transpile the .ts files and then start a node server.

Sometimes, the sub tasks have their own "watcher", to watch files changes and run the script again. For instanse, tsc script has the -w option, to watch changes in the .ts files to transpile them again.

The problem is, that "watch" scripts are never ending (unless we kill them, of course) so if we want to run them all, by doing script1 -w && script2 -w, script2 will never been execute because script1 will never ends.

Using | will not help us either because it will watch only the last part.

The solution

The solution is to use a package called npm-run-all. With this package we can run all the scripts in parallel and get all the outputs from all the scripts.

In https://github.com/moshfeu/y2mp3/blob/205c216dbaa6a4d9313d5a97828f2ce0b8aa39ed/package.json#L23 I needed to run 3 watchers: webpack, tsc, and electron so the package.json scripts was:

1"scripts": {
2 "tsc": "tsc -w",
3 "webpack": "webpack",
4 "electron": "electron ."
5}

So I added the start script:

1"scripts": {
2 "start": "npm-run-all --parallel tsc webpack electron",
3 "tsc": "tsc -w",
4 "webpack": "webpack",
5 "electron": "electron ."
6}

And that's it. Working like a charm :)

npm-run-all package

Thanks for @Ling for his answer: https://stackoverflow.com/a/39575186/863110

© 2022 - Moshe Feuchtwander