Home >Web Front-end >JS Tutorial >How Can I Pass Command Line Arguments to My npm Scripts?
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.
Starting with npm 2, passing arguments is straightforward:
npm run <command> [-- <args>]
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" } }
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`
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']
In contrast, using explicit -- removes ambiguity:
npm run test -- foobar ['C:\Program Files\nodejs\node.exe', 'C:\git\myrepo\test.js', 'foobar']
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!