How to run npm scripts concurrently?

Przemyslaw Jan Beigert - May 29 - - Dev Community

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.

. . . . . . . . . . .