61

Is there a way to pass arguments inside of the package.json command?

My script:

"scripts": {
  "test": "node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet"
}

cli npm run test 8080 production

Then on mytest.js I'd like to get the arguments with process.argv

Enzo
  • 4,111
  • 4
  • 21
  • 33

1 Answers1

69

Note: It only works on shell environment, not on Windows cmd. You should use bash on Windows like Git Bash. Or try Linux subsystem if you're using win10.

Passing arguments to script

To pass arguments to npm script, you should provide them after -- for safety.

In your case, -- can be omitted. They behaves the same:

npm run test -- 8080 production
npm run test 8080 production

But when the arguments contain option(s) (e.g. -p), -- is necessary otherwise npm will parse them and treat them as npm's option.

npm run test -- 8080 -p

Use positional parameters

The arguments are just appended to the script to be run. Your $1 $2 won't be resolved. The command that npm actually runs is:

node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet "8080" "production"

In order to make position variable works in npm script, wrap the command inside a shell function:

"scripts": {
  "test": "run(){ node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet; }; run"
}

Or use the tool scripty and put your script in an individual file.

package.json:

"scripts": {
  "test": "scripty"
}

scripts/test:

#!/usr/bin/env sh
node mytest.js $1 $2 | node_modules/tap-difflet/bin/tap-difflet
aleung
  • 9,848
  • 3
  • 55
  • 69
  • 1
    This doesn't seem to work on windows machines. I get the error: 'run' is not recognized as an internal or external command, operable program or batch file – Ben Southall Dec 05 '17 at 00:08
  • 2
    @BenSouthall Yes, it only works on shell environment, not on Windows cmd. You should use bash on Windows like Git Bash. Or try Linux subsystem if you're using win10. – aleung Dec 05 '17 at 06:05
  • 1
    I'm using Git Bash, but it still doesn't seem to work. – Ben Southall Dec 05 '17 at 23:11
  • This throws an error for me: `code ELIFECYCL; npm ERR! Exit status 1` @aleung – Union find Apr 13 '18 at 21:34
  • @incodeveritas Please first verify you script. See https://stackoverflow.com/questions/30744964/what-does-the-elifecycle-node-js-error-mean – aleung Apr 16 '18 at 03:35
  • https://github.com/Medium/phantomjs/issues/478 - getting Error: spawn UNKNOWN on Windows with scripty – danday74 Apr 11 '19 at 13:33