Home >Web Front-end >JS Tutorial >How Do I Pass Arguments to npm Scripts?

How Do I Pass Arguments to npm Scripts?

Linda Hamilton
Linda HamiltonOriginal
2024-12-04 02:02:151070browse

How Do I Pass Arguments to npm Scripts?

Passing Arguments to npm Scripts

npm allows passing arguments to scripts defined in the package.json file using the following syntax:

npm run <command> [-- <args>]

Example

Consider the following package.json:

"scripts": {
    "start": "node ./script.js server"
}

To start the server with a custom port, run the following command:

npm run start -- --port=8080

This will invoke the script with the server argument followed by the -port=8080 argument.

Separator

The -- separator is essential for distinguishing between arguments passed to npm and those passed to the script. Without the separator, npm may interpret script arguments as its own options.

Notes

  • If an argument does not start with - or --, the separator is not required but recommended for clarity.
  • Arguments starting with - or -- are passed to npm and not to the script.
  • To access argument values in the script, refer to process.argv.
  • Libraries like yargs or minimist can be used for parsing named parameters and extracting their values.

The above is the detailed content of How Do I Pass Arguments to npm Scripts?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn