Node NPM Scripts

NPM Scripts: Automating Node.js Tasks

As your Node.js project grows, you will find yourself typing the same long terminal commands over and over again. You might have a command to start the server, a command to run tests, and a command to compile your code.

NPM Scripts provide a way to save these long commands as easy-to-remember shortcuts inside your package.json file.


1. Defining Scripts in package.json

Open your package.json file. You will see an object property called "scripts". This object holds key-value pairs where the key is the name of your shortcut, and the value is the actual terminal command you want to execute.

package.json

{
  "name": "my-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "dev": "nodemon server.js",
    "say-hello": "echo \"Hello from NPM scripts!\""
  }
}

In the example above, we created three scripts:


2. Running NPM Scripts

To execute a script from your terminal, you use the npm run command, followed by the name of the script.

npm run dev

If you run the command above, NPM looks in your package.json, finds the "dev" script, and executes nodemon server.js on your behalf.

Special "Reserved" Scripts

NPM has a few script names that are considered standard across the industry. The most common is start (used to start the application) and test (used to run testing suites).

Because these are standard, NPM allows you to run them without the run keyword:

# Both of these work, but the first is preferred!
npm start
npm run start

(Note: Custom scripts like "dev" or "say-hello" MUST use npm run).


3. Pre and Post Hooks

NPM has an incredibly powerful feature called "hooks". If you prefix a script name with pre or post, NPM will automatically execute it before or after the main script!

package.json

{
  "scripts": {
    "prebuild": "echo \"Cleaning old files...\"",
    "build": "echo \"Compiling code...\"",
    "postbuild": "echo \"Build complete! Uploading...\""
  }
}

If you type npm run build in the terminal, NPM will sequentially run prebuild, then build, and finally postbuild, completely automatically!


Exercise

?

Given a custom script named "format" in package.json, what is the correct command to execute it?