Package JSON scripts (NPM Scripts)

Muhammad SaifMuhammad Saif
2 min read

Introduction

Package JSON scripts, often referred to as npm scripts, are custom commands defined in the package.json file of a Node.js project. These scripts automate terminal commands, making it easier to perform repetitive or complex tasks with simple keywords. By using npm scripts, developers can streamline their workflows, reduce manual intervention, and maintain consistency across development environments.

How to define the script

Open package.json file and add a script property which is going to be an object in the form “key” : value.

{
  "scripts": {
    "start": "node app.js",
    "lint": "eslint .",
    "build": "webpack --mode production",
    "test": "jest",
    "clean": "rm -rf dist/"
  }
}

Here the value is the command that you want to execute on your OS just like you would do on a shell.

How do we run the script

We can run the script by passing the key to npm run command.

npm run <key>

// Example: npm run dev

Example : Running ‘mkdir’ and ‘rm’ command through npm scripts

Create a test directory, change your directory to test and initialize npm to generate package.json file.

mkdir test && cd test && npm init -y

Add your commands under the scripts property.

{
  "name": "test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "print": "mkdir npm_script_works",
    "clean": "rm -r npm_script_works"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

Run the following command.

npm run print

You should see that a directory with the name “npm_script_works” has been created.

References : Introduction to Package JSON Scripts in Node.js: A Guide for Optimizing Your Development Workflow

https://www.upgrad.com/blog/introduction-to-package-json-scripts-in-node-js/

0
Subscribe to my newsletter

Read articles from Muhammad Saif directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Muhammad Saif
Muhammad Saif