2

I want to write npm scripts which run when bumping the package version via npm version. I do not intend for my scripts to be invoked directly via npm run _____; instead, they should be invoked by npm, when npm version ____ (or preversion or postversion, etc) is called.

How can I refer to the version level argument in my scripts?

e.g. If my script runs as preversion and was invoked from npm version major, how can my script refer to major?

tuff
  • 4,895
  • 6
  • 26
  • 43
  • Possible duplicate of [Pass command line args to npm scripts in package.json](https://stackoverflow.com/questions/51388921/pass-command-line-args-to-npm-scripts-in-package-json) – jakemingolla Jun 10 '19 at 19:49
  • Sorry, can you please explain how I can use the solution to that question to answer mine? I am not writing an arbitrary script which is invoked directly by `npm run myScript`; instead `myScript` is invoked on the `version` lifecycle hook. The `npm version` command already takes an argument and does its own validation on that. I simply want to refer to the value of that arg within `myScript`. – tuff Jun 18 '19 at 20:30

1 Answers1

3

Within my script, I can refer to process.env.npm_config_argv. Its value is a JSON string which contains the original args to npm.

If my package.json contains:

"scripts": {
  "preversion": "node log_argv"
}

And log_argv.js contains:

console.log('Type:', typeof process.env.npm_config_argv);
console.log('Value:', process.env.npm_config_argv);
console.log('Original npm args:', JSON.parse(process.env.npm_config_argv).original);

throw new Error("aborting");

And I run npm version patch, then I see the output:

Type: string
Value: {"remain":["patch"],"cooked":["version","patch"],"original":["version","patch"]}
Original npm args: [ 'version', 'patch' ]
tuff
  • 4,895
  • 6
  • 26
  • 43