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

How Can I Pass Command Line Arguments to npm Scripts?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-04 14:23:11688browse

How Can I Pass Command Line Arguments to npm Scripts?

Passing Command Line Arguments to npm Scripts

Javascript developers often ask how to pass command line arguments when executing npm scripts.

Solution for npm 2 and Newer

In npm versions 2 and later, you can pass arguments using the following syntax:

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

The -- separator helps distinguish between arguments passed to npm and those passed to your script.

For example, given the package.json below:

{
  "scripts": {
    "grunt": "grunt",
    "server": "node server.js"
  }
}

You can execute these scripts with arguments as follows:

npm run grunt -- task:target
npm run server -- --port=1337

Note: If your argument doesn't begin with - or --, it's not necessary to use the -- separator, but for clarity, it's recommended.

However, parameters starting with - or -- are passed to npm and not to the script.

To extract argument values, you can utilize process.argv or a library like yargs or minimist.

The above is the detailed content of How Can I Pass Command Line 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