1

I have some npm scripts that look like this:

"scripts": {
    "exec:dev": "export NODE_ENV=development && npm run exec",
    "exec:stage": "export NODE_ENV=stage && npm run exec",
    "exec:prod": "export NODE_ENV=production && npm run exec",
    "exec": "node myapp.js"
}

I'd like to pass some command line arguments to myapp.js but this does not work:

npm run exec:prod -- -a 123 -b 456

This is apparently due to the fact that the exec:prod script is calling the exec script and apparently not passing along the command line parameters. Is there any way to achieve this while keeping the nested script calls?

2 Answers 2

5

To explicitly tell the exec script to pass along the arguments it gets, include another --.

Instead of:

npm run exec:prod -- -a 123 -b 456

try:

npm run exec:prod -- -- -a 123 -b 456

  • The first double dash tells the exec:dev script, "these args aren't for you, pass them along to the exec script".

  • The second double dash tells the exec script, "these args aren't for you, pass them along to node myapp.js".

Sign up to request clarification or add additional context in comments.

Comments

3
+50

If you want to keep the npm run command that you enter via the CLI the same as per your question. (i.e. avoid adding yet another npm special option (--) to it, as per @MikePatrick 's answer).

Change your npm-scripts to the following instead:

"scripts": {
    "exec:dev": "export NODE_ENV=development && npm run exec --",
    "exec:stage": "export NODE_ENV=stage && npm run exec --",
    "exec:prod": "export NODE_ENV=production && npm run exec --",
    "exec": "node myapp.js"
}

Note: the npm special option (--) added to the end of the first three scripts.


Demo

For demonstration purposes, lets say myapp.js is as follows:

myapp.js

const args = (process.argv.slice(2));
const nodeEnv = process.env.NODE_ENV;

console.log(nodeEnv);
console.log(args);

Testing:

  • Running npm run exec:dev -- -a 123 -b 456 prints:

    development

    [ '-a', '123', '-b', '456' ]

  • Running npm run exec:stage -- -a 123 -b 456 prints:

    stage

    [ '-a', '123', '-b', '456' ]

  • Running npm run exec:prod -- -a 123 -b 456 prints:

    production

    [ '-a', '123', '-b', '456' ]


Further info

The docs for npm-run-script describe the npm special option (--) as follows:

... The special option -- is used by getopt to delimit the end of the options. npm will pass all the arguments after the -- directly to your script ... The arguments will only be passed to the script specified after npm run and not to any pre or post script.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.