How to run npm scripts concurrently?
Przemyslaw Jan Beigert

Przemyslaw Jan Beigert @przemyslawjanbeigert

About: Software engineer, enthusiast of new technologies (but only if they are better than old ones). Open source and functional programming fan.

Location:
Poznan, Poland
Joined:
Nov 2, 2021

How to run npm scripts concurrently?

Publish Date: May 29 '24
18 2

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.

Comments 2 total

  • Massimo Artizzu
    Massimo ArtizzuMay 29, 2024

    Concurenct

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

    Plus: it works on Windows.

  • Michael J. Ryan
    Michael J. RyanMay 29, 2024

    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

Add comment