Mastering npm Run Script Understanding npm Run Script with Examples and Tips

Introduction to npm-run-script

The npm-run-script command is a powerful feature of Node.js that allows developers to define and run custom scripts inside their projects. This command helps automate repetitive tasks, streamline development workflows, and consistently run predefined tasks. In this post, we’ll explore the various APIs and provide examples for better understanding.

Basic Usage


// package.json
{
  "scripts": {
    "start": "node app.js",
    "test": "jest",
    "build": "webpack"
  }
}

To run a script, use the command: npm run <script-name>. For example:

 npm run start

Common npm-run-script APIs

Pre and Post Hooks

npm automatically executes pre and post hooks if they are defined in the package.json.


{
  "scripts": {
    "prebuild": "npm run lint",
    "build": "webpack",
    "postbuild": "npm test"
  }
}

Execute Multiple Scripts

You can run multiple scripts sequentially using && and concurrently using |.


{
  "scripts": {
    "build": "npm run lint && webpack",
    "test-all": "npm run test:unit | npm run test:e2e"
  }
}

Pass Arguments to Scripts

Arguments can be passed to the scripts:

npm run script-name -- --arg1 value1

App Example

Here’s a simple example of an application with a few defined scripts.


// package.json
{
  "name": "sample-app",
  "version": "1.0.0",
  "scripts": {
    "start": "node app.js",
    "build": "node build.js",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "jest": "^26.6.3",
    "eslint": "^7.14.0"
  }
}


// app.js
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(port, () => {
  console.log(`App running at http://localhost:${port}`);
});

To start the app, use: npm run start

To lint the code: npm run lint

To run tests: npm run test

To build the project: npm run build

By using npm-run-script effectively, you can greatly simplify your project workflows and maintain consistency across development tasks.

Hash: 1414c2d93afe61f056cf9d7ac1165801f0a6f07c479caf40c223149c7be4ff4e

Leave a Reply

Your email address will not be published. Required fields are marked *