How can I run multiple npm scripts in parallel?

How can I run multiple npm scripts in parallel?

In my package.json I have these two scripts:
“scripts”: {
“start-watch”: “nodemon run-babel index.js”,
“wp-server”: “webpack-dev-server”,
}

I have to run these 2 scripts in parallel everytime I start developing in Node.js. The first thing I thought of was adding a third script like this:
“dev”: “npm run start-watch && npm run wp-server”

… but that will wait for start-watch to finish before running wp-server.
How can I run these in parallel? Please keep in mind that I need to see the output of these commands. Also, if your solution involves a build tool, I’d rather use gulp instead of grunt because I already use it in another project.

Solutions/Answers:

Solution 1:

Use a package called concurrently.

npm i concurrently --save-dev

Then setup your npm run dev task as so:

"dev": "concurrently --kill-others \"npm run start-watch\" \"npm run wp-server\""

Solution 2:

Using the Concurrently package works, but you do not need it to accomplish this. You can just use a pipe on UNIX based machines run concurrent tasks. I would suggest this method over the other because it saves you from having to add an additional dependency.

"dev": "npm run start-watch > /dev/null | npm run wp-server"

note: the first command will have its output ignored

Solution 3:

If you’re using an UNIX-like environment, just use & as the separator:

"dev": "npm run start-watch & npm run wp-server"

Otherwise if you’re interested on a cross-platform solution, you could use npm-run-all module:

"dev": "npm-run-all --parallel start-watch wp-server"

Solution 4:

From windows cmd you can use start:

"dev": "start npm run start-watch && start npm run wp-server"

Every command launched this way starts in its own window.

Solution 5:

You should use npm-run-all (or concurrently, parallelshell), because it has more control over starting and killing commands. The operators &, | are bad ideas because you’ll need to manually stop it after all tests are finished.

This is an example for protractor testing through npm:

scripts: {
  "webdriver-start": "./node_modules/protractor/bin/webdriver-manager update && ./node_modules/protractor/bin/webdriver-manager start",
  "protractor": "./node_modules/protractor/bin/protractor ./tests/protractor.conf.js",
  "http-server": "./node_modules/http-server/bin/http-server -a localhost -p 8000",
  "test": "npm-run-all -p -r webdriver-start http-server protractor"
}

-p = Run commands in parallel.

-r = Kill all commands when one of them finishes with an exit code of zero.

Running npm run test will start Selenium driver, start http server (to serve you files) and run protractor tests. Once all tests are finished, it will close the http server and the selenium driver.

Solution 6:

A better solution is to use &

"dev": "npm run start-watch & npm run wp-server"