With npm or yarn, is it possible for the script specified by an npm script to know the name of the npm script itself? For example:
"scripts": {
"foo": "echo Original command: $0",
"bar": "echo Original command: $0"
}
I'd like the result of those two scripts to be something like:
Original command: yarn run foo
Original command: yarn run bar
But all I actually get is: Original command: /bin/sh
.
And in case it makes a difference, it's just the name of the script I need, not the yarn run
part, so output like Original command: foo
would be fine.
NPM adds the npm_lifecycle_event
environment variable. It's similar to package.json vars.
On *nix platforms npm utilizes sh
as the default shell for running npm scripts, therefore your scripts can be defined as:
"scripts": {
"foo": "echo The script run was: $npm_lifecycle_event",
"bar": "echo The script run was: $npm_lifecycle_event"
}
Note: The dollar prefix $
to reference the variable.
On Windows npm utilizes cmd.exe
as the default shell for running npm scripts, therefore your scripts can be defined as:
"scripts": {
"foo": "echo The script run was: %npm_lifecycle_event%",
"bar": "echo The script run was: %npm_lifecycle_event%"
}
Note: The leading and trailing percentage sign %
used to reference the variable.
For cross-platform you can either:
Utilize cross-var to enable a single syntax, i.e. using the dollar sign prefix $
as per the *nix syntax.
Or, utilize the node.js command line option -p
to evaluate and print the result of the following inline JavaScript:
"scripts": {
"foo": "node -e \"console.log('The script run was:', process.env.npm_lifecycle_event)\"",
"bar": "node -e \"console.log('The script run was:', process.env.npm_lifecycle_event)\""
}
Note In this example we:
npm_lifecycle_event
environment variable using the node.js process.env property.console.log
(instead of echo
) to print the result to stdout