有没有办法将 npm 脚本的名称传递给该脚本指定的命令?
Is there a way to get the name of the npm script passed to the command specified by that script?
对于npm或yarn,npm脚本指定的脚本是否可以知道npm脚本本身的名称?例如:
"scripts": {
"foo": "echo Original command: [=10=]",
"bar": "echo Original command: [=10=]"
}
我希望这两个脚本的结果类似于:
Original command: yarn run foo
Original command: yarn run bar
但我实际得到的是:Original command: /bin/sh
。
如果它有所不同,它只是我需要的脚本的名称,而不是 yarn run
部分,所以像 Original command: foo
这样的输出就可以了。
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:
在 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、...)
对于跨平台,您可以:
利用 cross-var 启用单一语法,即根据 *nix 语法使用美元符号前缀 $
。
或者,利用 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
对于npm或yarn,npm脚本指定的脚本是否可以知道npm脚本本身的名称?例如:
"scripts": {
"foo": "echo Original command: [=10=]",
"bar": "echo Original command: [=10=]"
}
我希望这两个脚本的结果类似于:
Original command: yarn run foo
Original command: yarn run bar
但我实际得到的是:Original command: /bin/sh
。
如果它有所不同,它只是我需要的脚本的名称,而不是 yarn run
部分,所以像 Original command: foo
这样的输出就可以了。
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:
在 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、...)
对于跨平台,您可以:
利用 cross-var 启用单一语法,即根据 *nix 语法使用美元符号前缀
$
。或者,利用 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 属性. 访问
- 利用
console.log
(而不是echo
)将结果打印到stdout
npm_lifecycle_event
环境变量