The Absolute Best Way to Run Multiple npm Scripts in Parallel in 2022

swyx

2 reactions 2022-10-11

Why do you want to run multiple scripts? Multiple reasons, for example you want to run a backend server process and a frontend app process, and kick them off with one command. You can’t write npm start frontend && npm start backend because && requires the first process to terminate first. (I think) You also don’t want to write npm start frontend & npm start backend because if one process ends for whatever reason you want the other to end as well (makes it easier to blindly Ctrl+C and rerun the same command when you run into trouble).

There are two leaders in the parallel npm scripts game: concurrently and npm-run-all:

https://npmcharts.com/compare/concurrently,npm-run-all?interval=30

image

Both have very similar features but we will just focus on concurrently as it is sliiiightly more flexible and nicely documented (this is not a strong opinion).

Step 1 - Install the thing

Do I really need to explain?

npm i -D concurrently

Step 2 - Setup Concurrently

Assuming you have two scripts in package.json you want to run concurrently:

	"scripts": {
		"dev": "vite dev",
		"story:dev": "histoire dev",
		"start": "concurrently \"npm run dev\" \"npm run story:dev\"",
	}

Now you can start them with npm start!

image

But wait, this log output is a bit hard to read. Can we do better?

This is the beautiful third step.

Step 3 - Name and Color

	"scripts": {
		// omitted...
		"start": "concurrently --names \"APP,HISTOIRE\" -c \"bgBlue.bold,bgMagenta.bold\" \"npm run dev\" \"npm run story:dev\"",
	}

image

Now you can tell at a glance where logs are coming from!

Get updates on new posts and projects

3000+ subscribers including my Mom – see past issues

Reactions: ❤️ 2
Webmentions
Loading...