Course contentsShow
← JavaScript
Lesson 2512 of 2,72351. Package ManagementFree lesson

Running Scripts with npm run

Executing defined scripts using npm run and understanding the script execution environment.

Running Scripts with npm run

You'll learn how to execute your package.json scripts using npm run and understand what happens behind the scenes when they run.

The npm run Command

Once you've defined scripts in your package.json (covered in the previous lesson), you execute them with npm run <script-name>. This command tells npm to look up that script name and run the associated command in a special environment.

// package.json
{
  "scripts": {
    "build": "webpack --mode production",
    "test": "jest",
    "custom": "echo Hello from custom script"
  }
}

To run these scripts:

npm run build
npm run test
npm run custom

The Script Execution Environment

When npm runs a script, it temporarily modifies the PATH environment variable. It prepends ./node_modules/.bin to your PATH, which means executables from locally installed packages take precedence. This is why you can write "webpack" instead of "./node_modules/.bin/webpack" in your scripts.

Think of it like npm temporarily renting out a special workshop where all your tools are already on the workbench—you don't need to know where they're stored.

Special Script Shortcuts

Some scripts have built-in shortcuts and don't require npm run:

  • npm test (shortcut for npm run test)
  • npm start (shortcut for npm run start)

But most custom scripts need the full npm run command.

Viewing Available Scripts

Run npm run with no arguments to see all available scripts in your package:

npm run

This lists every script defined in your package.json, making it easy to discover what commands are available.

Key Takeaway: npm run <script-name> executes package.json scripts in an environment where locally installed packages are automatically accessible, eliminating the need for global installations or path manipulation.