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

How Do I Pass Command Line Arguments to npm Scripts?

Barbara Streisand
Release: 2024-12-08 05:47:09
Original
285 people have browsed it

How Do I Pass Command Line Arguments to npm Scripts?

Passing Command Line Arguments to NPM Scripts

In order to pass command line arguments to npm scripts, it is essential to understand that the syntax has changed depending on the version of npm you are using.

npm 2 and Newer

Starting with npm 2, you can pass arguments to npm run using the following syntax:

"npm run [command] [-- [args]]"

Here, the "--" separator is used to separate the parameters passed to the npm command itself from the parameters passed to your script.

For example, you could have a package.json with the following scripts:

"scripts": {

"grunt": "grunt",
"server": "node server.js"
Copy after login

}

To pass parameters to these scripts, you would use commands like:

npm run grunt -- task:target // invokes "grunt task:target"
npm run server -- --port=1337 // invokes "node server.js --port=1337"

Notes:

  • If your parameter does not start with "-" or "--", you can still pass it without the "--" separator, but it is recommended to use it for clarity.
  • Parameters starting with "-" or "--" are passed to npm and not to the script, effectively silencing them.

Getting Parameter Values

To retrieve parameter values, you can consult the process.argv global variable in Node.js. This variable holds an array containing the command line parameter values. Alternatively, you can use argument parsing libraries like yargs or minimist for more advanced parameter handling.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template