swyxio / swyxdotio

This is the repo for swyx's blog - Blog content is created in github issues, then posted on swyx.io as blog pages! Comment/watch to follow along my blog within GitHub
https://swyx.io
MIT License
325 stars 43 forks source link

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

Closed swyxio closed 1 year ago

swyxio commented 1 year ago

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 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!

devinrhode2 commented 1 year ago

I think npm-run-all, which I just happen to have used, also supports labeled output. Doesn't support colors tho, iirc.

jaens commented 5 months ago

This does not actually need any extra packages at all, just a better package manager :smile:

Using the pnpm package manager, just use a regex to run multiple scripts concurrently, eg.

$ pnpm run /^build:/
raucher commented 2 months ago

Very helpful, tnx!