问题
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.
回答1:
NPM adds the npm_lifecycle_event
environment variable. It's similar to package.json vars.
*Nix (Linux, macOS, ... )
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.
Windows:
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.
Cross-platform (Linux, macOS, Windows, ... )
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:
- Access the
npm_lifecycle_event
environment variable using the node.js process.env property. - Utilize console.log (instead of
echo
) to print the result tostdout
- Access the
来源:https://stackoverflow.com/questions/62865856/is-there-a-way-to-get-the-name-of-the-npm-script-passed-to-the-command-specified