DEV Community

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Posted on

How to run npm scripts concurrently?

Intro

Before creating a pull request, you probably want to be sure that CI will reject it. So before gh pr create you're running npm run lint or npm run test. npm run build etc.

Script

To avoid manually calling each script you can define a new script in the package.json.

{
  "scripts": {
    "ci:check": "npm run lint && npm run test && npm run build"
  }
}
Enter fullscreen mode Exit fullscreen mode

first && second in bash means: when the first returns success then run the second one. If fails, stop the execution and return this fail value.

Package

There's a package to speed this command up. Concurrently

{
  "scripts": {
    "ci:check": "concurrently \"npm run lint\" \"npm run test\" \"npm run build\""
  }
}
Enter fullscreen mode Exit fullscreen mode

Now ci:check will start each check concurrently. The total execution time will be the longest-running script, rather than the sum of all three.

Bash

But do we need a package for that? Such a simple thing can be done just with a bash language.

first & second will run both commands in the same moment, but the result of that will be the result of the second one. So if the first fails final result will be positive.

FG - Place the job in the foreground, and make it the current job using the fg command.

{
  "scripts": {
    "ci:check": "npm run lint & npm run test & npm run build && fg"
  }
}
Enter fullscreen mode Exit fullscreen mode

However, this approach runs all checks simultaneously but reports the exit status of the last command, similar to a sequential execution.

Summary

Learn bash.

Top comments (2)

Collapse
 
maxart2501 profile image
Massimo Artizzu

Concurenct

You literally wrote concurrently in the script... (And that's the correct name.)

Plus: it works on Windows.

Collapse
 
tracker1 profile image
Michael J. Ryan

As much as I dislike Windows, and even in Windows will prefer WSL... Windows development is still a thing and I try to be friendly to Windows developers as much as reasonable.

That's why Concurrently exists even if there's Bash on Mac, Linux, BSD, etc.

echojs.com/comment/42401/1