How to run a npm script after main npm script fails?

Viewed 2183

My main npm script is "npm run build".

What I want to do is write another script that would execute like a catch in exception handling whenever "npm run build" fails.

1 Answers

You can utilize the OR operator (||) in an npm script. It is supported by both sh and cmd.exe so it works cross-platform.

Consider the following example in the scripts section of package.json:

"scripts": {
  "build": "<your build script here> || npm run fallback",
  "fallback": "echo \"Oops! Running another script....\""
},

Explanation:

  1. Your current build script command should replace the <your build script here> part in the build script.
  2. The fallback script will only run if your build command on the left side of the || operator exits with a non-zero exit status (i.e. if it fails).
  3. When your build script command exits successfully (i.e. with a zero exit code) the npm run fallback part on the right side of the || operator never gets invoked.
  4. The "echo \"Oops! Running another script....\"" in the fallback script should be replaced with the command(s) that you want to execute when build fails.

The example above utilizes another script named fallback mainly for explanatory purposes, however you can just have one build script, For instance:

"scripts": {
  "build": "<your build script here> || echo \"Oops! Running another script...\""
},
Related