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

How Can I Pass Command Line Arguments to My npm Scripts?

Mary-Kate Olsen
Release: 2024-12-12 15:22:11
Original
557 people have browsed it

How Can I Pass Command Line Arguments to My npm Scripts?

Sending Command Line Arguments to npm Script

When it comes to npm scripts, there's often a desire to pass arguments from the command line to the script being executed. Let's delve into how to accomplish this.

npm 2 and Newer

Starting with npm 2, passing arguments is straightforward:

npm run <command> [-- <args>]
Copy after login

The crucial element here is the -- separator. It distinguishes between arguments intended for npm and those meant for your script.

For example, with the package.json snippet below:

{
  "scripts": {
    "grunt": "grunt",
    "server": "node server.js"
  }
}
Copy after login

You can pass arguments as follows:

npm run grunt -- task:target  // invokes `grunt task:target`
npm run server -- --port=1337 // invokes `node server.js --port=1337`
Copy after login

Note: Explicit -- separation is recommended even when arguments don't start with - or --. Consider:

npm run test foobar
['C:\Program Files\nodejs\node.exe', 'C:\git\myrepo\test.js', 'foobar']
Copy after login

In contrast, using explicit -- removes ambiguity:

npm run test -- foobar
['C:\Program Files\nodejs\node.exe', 'C:\git\myrepo\test.js', 'foobar']
Copy after login

To access parameter values within your script, refer to process.argv. Alternatively, consider using parsing libraries such as yargs or minimist for greater flexibility in handling arguments, including named parameters.

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

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