The Front-End
Package Managers
Npm Scripts

Npm and Yarn Scripts

  1. npm Scripts
  2. Creating and Running Custom Scripts
  3. Integrating Scripts into Development Workflows

npm Scripts

Creating and Running Custom Scripts:

Defining Scripts in package.json:

In the scripts section of your package.json file, you can define custom scripts. Here's a basic example:

{
  "scripts": {
    "start": "node index.js",
    "test": "mocha tests/*.js",
    "build": "babel src -d dist"
  }
}

In this example:

  • "start" runs your application.
  • "test" executes your testing suite using Mocha.
  • "build" transpiles your source code using Babel.

Running Scripts:

To execute a script, use the npm run command:

npm run start

This will run the script named "start" defined in your package.json.

Integrating Scripts into Development Workflows:

Pre and Post Hooks:

npm allows you to define pre and post hooks for scripts. For example, if you want to run a setup script before your actual "start" script, you can define a "prestart" script:

{
  "scripts": {
    "prestart": "setup.sh",
    "start": "node index.js"
  }
}

Now, when you run npm run start, it will automatically execute the "prestart" script before the main "start" script.

Chaining Scripts:

You can chain multiple scripts together using the && operator. For instance, to run linting before testing:

{
  "scripts": {
    "lint": "eslint .",
    "test": "npm run lint && mocha tests/*.js"
  }
}

Now, when you run npm run test, it first executes the "lint" script, and if that succeeds, it proceeds to run the testing script.

Passing Arguments to Scripts:

You can pass arguments to your scripts using the -- separator. For example, to pass an environment variable to the "start" script:

{
  "scripts": {
    "start": "NODE_ENV=production node index.js"
  }
}

Now, running npm run start will set the NODE_ENV variable before executing the script.

Useful Commands:

  • Listing Available Scripts:

    npm run
  • Running Scripts with Arguments:

    npm run start -- arg1 arg2
  • Executing Predefined Scripts:

    npm test

npm scripts provide a powerful mechanism for automating common development tasks. Customizing and integrating scripts into your workflow enhances efficiency and promotes consistency across development, testing, and build processes. Understanding how to create, chain, and pass arguments to npm scripts empowers developers to tailor their development environment to meet specific project requirements.