有没有办法获取传递给该脚本指定的命令的 npm 脚本的名称? [英] Is there a way to get the name of the npm script passed to the command specified by that script?

查看:69
本文介绍了有没有办法获取传递给该脚本指定的命令的 npm 脚本的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用npm或yarn,npm脚本指定的脚本是否有可能知道npm脚本本身的名称?例如:

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

但我实际得到的是:原始命令:/bin/sh.

如果它有所不同,它只是我需要的脚本的名称,而不是 yarn run 部分,因此像 Original command: foo 这样的输出将是很好.

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 添加了 npm_lifecycle_event 环境变量.它类似于 package.json vars.

NPM adds the npm_lifecycle_event environment variable. It's similar to package.json vars.

*nix 平台上,npm 使用 sh 作为运行 npm 脚本的默认 shell,因此您的脚本可以定义为:

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 上,npm 使用 cmd.exe 作为运行 npm 脚本的默认 shell,因此您的脚本可以定义为:

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.

对于跨平台,您可以:

  1. 利用 cross-var 启用单一语法,即使用美元符号前缀 $ 按照 *nix 语法.

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

或者,使用 node.js 命令行选项 -p 评估并打印以下内联 JavaScript 的结果:

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

这篇关于有没有办法获取传递给该脚本指定的命令的 npm 脚本的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆