npm npm scripts What npm scripts are and how are they triggered


Example

The npm scripts are commands that npm will run for you when called with the proper arguments. The power and sense of this is to NOT install the npm packages globally poluting your environment.

The difference between pre-recognized and custom scripts relies on the run word between the tags, custom scripts will need the run between npm and the script name

Based on this we can differenciate and create different tasks or scripts to be run with npm.

Given the following example on the package.json file:

{
  "name": "MyApp",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "mocha --recursive ./tests/",
    "test:watch": "npm run test -- -w",
    "start": "nodemon --inspect ./app.js",
    "build": "rm -rf ./dist/ && gulp build"
  }
...
}

We can see different tasks to be run:

  • npm test Would work fine as it is a pre-recognized script

  • npm run test Would work fine as it is a valid way to execute a npm script

  • npm run test:watch Would work also, and it's calling npm run test inside itself

  • npm run build Would before running gulp build delete the dist folder that is in the directory (assuming you are in Linux or the command rm is recognized)