Explain Codes LogoExplain Codes Logo

How can I run multiple npm scripts in parallel?

javascript
prompt-engineering
process-management
package-json
Alex KataevbyAlex Kataev·Nov 10, 2024
TLDR

To run multiple npm scripts in parallel, you can utilize concurrently or npm-run-all. These are dev dependencies that go into your package.json.

Concurrently:

"scripts": { "parallel": "concurrently 'npm:script1' 'npm:script2'" }

Run with: npm run parallel. // Where's the party at? It's at parallel o'clock

npm-run-all:

"scripts": { "parallel": "npm-run-all -p script1 script2" }

Run with: npm run parallel. // Parallel is not just a math term anymore!

concurrently – the saviour for your terminal

When engaging with concurrently, count on the --kill-others option. It helps in stopping all scripts when one fails, which avoids the horror of zombie processes:

"scripts": { "parallel": "concurrently --kill-others 'npm:script1' 'npm:script2'" }

npm-run-all – the cross-platform peacekeeper

If you're after cross-platform compatibility, then hail npm-run-all. It offers a nifty short form, run-p, to execute scripts in parallel:

"scripts": { "parallel": "npm-run-all -p script1 script2" }

But there's more, with -r flag, if one script finishes, all other scripts stop. It's like a well-contected relay race:

"scripts": { "serial-kill": "npm-run-all -r script1 script2" }

Marrying gulp with concurrently or npm-run-all

If gulp is your preferred build tool, pair it with concurrently or npm-run-all for better control and output visibility. Keeping track of multiple processes has never been easier!

const gulp = require('gulp'); const concurrently = require('concurrently'); gulp.task('serve', () => { concurrently([ 'gulp watch', // I watch changes like a hawk 'gulp serve' // Serving you right since 2013 ]); });

Taking care of complex script dependencies and process management

If your scripts have complex dependencies or if you need robust process management, consider using PM2. It's like a babysitter for your node processes. For smaller tasks, structure your scripts into mini npm commands that manage their own responsibilities.

Structuring package.json for maintainability and scalability

Large project? Complex scripts? Organize your `package.json for smoother navigation and efficient execution:

"scripts": { "dev:ssr": "npm run build:watch & npm run serve:ssr", "build:watch": "gulp watch --gulpfile gulpfile-esm.mjs", // Keep those eyes peeled for changes "serve:ssr": "node dist/server", // Let's get cracking! "test:watch": "npm-run-all -p watch:*", // We're watching... always watching... "watch:tests": "jest --watch", // Jest-ing around with watches "watch:lint": "eslint --watch" //eslint, watching your code since 2013 }