【问题标题】:Is there a way to get the name of the npm script passed to the command specified by that script?有没有办法将 npm 脚本的名称传递给该脚本指定的命令?
【发布时间】:2020-11-02 01:24:33
【问题描述】:

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

"scripts": {
  "foo": "echo Original command: $0",
  "bar": "echo Original command: $0"
}

我希望这两个脚本的结果类似于:

Original command: yarn run foo
Original command: yarn run bar

但我实际上得到的只是:Original command: /bin/sh

如果它有所作为,它只是我需要的脚本的名称,而不是 yarn run 部分,所以像 Original command: foo 这样的输出就可以了。

【问题讨论】:

    标签: npm yarnpkg npm-scripts


    【解决方案1】:

    NPM 添加了npm_lifecycle_event 环境变量。类似于package.json vars

    *Nix (Linux, macOS, ... )

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

    "scripts": {
      "foo": "echo The script run was: $npm_lifecycle_event",
      "bar": "echo The script run was: $npm_lifecycle_event"
    }
    

    注意:美元前缀$ 来引用变量。

    窗口:

    在 Windows 上,npm 使用cmd.exe 作为运行 npm 脚本的默认 shell,因此您的脚本可以定义为:

    "scripts": {
      "foo": "echo The script run was: %npm_lifecycle_event%",
      "bar": "echo The script run was: %npm_lifecycle_event%"
    }
    

    注意:前导百分号%用于引用变量。

    跨平台(Linux、macOS、Windows...)

    对于跨平台,您可以:

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

    2. 或者,利用 node.js 命令行选项-p 来评估并打印以下内联 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)\""
      }
      

      注意在这个例子中我们:

      • 使用 node.js 的process.env 属性访问npm_lifecycle_event 环境变量。
      • 利用console.log(而不是echo)将结果打印到stdout

    【讨论】:

      猜你喜欢
      • 2017-07-18
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2020-05-09
      • 2018-07-23
      相关资源
      最近更新 更多