Is there a way to get the name of the npm script passed to the command specified by that script?

半腔热情 提交于 2021-02-05 09:14:07

问题


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:

  1. Utilize cross-var to enable a single syntax, i.e. using the dollar sign prefix $ as per the *nix syntax.

  2. 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 to stdout


来源:https://stackoverflow.com/questions/62865856/is-there-a-way-to-get-the-name-of-the-npm-script-passed-to-the-command-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!