tuff
tuff

Reputation: 5153

Get version level from npm script

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?

Upvotes: 3

Views: 584

Answers (1)

tuff
tuff

Reputation: 5153

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' ]

Upvotes: 3

Related Questions