LinuxCommandLibrary

npm-run

Execute scripts defined in package.json

TLDR

Run a script

$ npm run [script_name]
copy

Pass arguments to a script
$ npm run [script_name] -- [argument] [--option]
copy

Run a script named start
$ npm start
copy

Run a script named stop
$ npm stop
copy

Run a script named restart
$ npm restart
copy

Run a script named test
$ npm test
copy

SYNOPSIS

npm run [script-name] [-- ...args]

PARAMETERS

script-name
    The name of the script to execute, as defined in the 'scripts' section of package.json.

-- ...args
    Optional arguments passed to the script being executed.

DESCRIPTION

The `npm run` command allows you to execute arbitrary script commands defined in your project's `package.json` file.

The `package.json` file contains a `scripts` section, which is a JSON object where each key represents a script name and the corresponding value is the command to be executed. `npm run ` will execute the specified command in a shell environment with appropriate environment variables set up, including the project's `node_modules/.bin` directory in the `PATH`. This allows you to use locally installed dependencies without specifying their full paths.

This command is incredibly useful for automating common tasks such as building, testing, linting, starting development servers, and deploying applications. It promotes consistency across development environments because the script definitions are part of the project itself. Using `npm run` significantly simplifies project management and streamlines workflows. The command provides a standard method for executing tasks, rather than requiring developers to remember specific commands or rely on different tools.

CAVEATS

If no `script-name` is provided, `npm run` will list the available scripts in the current project.
If a script with the given name is not found, `npm run` will exit with an error.
Scripts are executed using `sh` on Unix-like systems and `cmd` on Windows. You can use `cross-env` if you need to set environment variables in a cross-platform way.

ENVIRONMENT VARIABLES

When running a script, npm sets a number of environment variables, including those prefixed with `npm_package_`. These variables provide access to the package's metadata, such as name, version, and dependencies. Accessing these variables can be useful for customizing the script's behavior.
See the npm documentation for a comprehensive list.

LIFECYCLE SCRIPTS

npm also defines a set of lifecycle scripts, such as `preinstall`, `postinstall`, `prepublishOnly`, etc. These scripts are automatically executed by npm during package installation and publishing. You can define these scripts in your `package.json` file to perform actions before or after specific npm commands.

SEE ALSO

npm(1), package.json(5)

Copied to clipboard