The Absolute Best Way to Run Multiple npm Scripts in Parallel in 2022
swyxio opened this issue · comments
category: tutorial
slug: parallel-npm-scripts
description: Just a quick tutorial and explanation of how best to set up concurrently with named and colored log output since I had to look it up today.
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 writenpm 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
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
!
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\"",
}
Now you can tell at a glance where logs are coming from!
I think npm-run-all, which I just happen to have used, also supports labeled output. Doesn't support colors tho, iirc.