假设我有这样的东西:
{
"scripts": {
"clean": "some-clean-script",
"prebuild": "npm run clean",
"build": "some-build-script"
}
}
在我的 some-clean-script
(用 NodeJS 编写)中,我想知道脚本是作为 prebuild
的一部分运行还是被直接调用.
我该怎么做?
最佳答案
在env.process
下有一个名为npm_lifecycle_event
的变量,它存储了package.json
中表示脚本名称的key。所以在你的情况下,你可以检查是否 process.env.npm_lifecycle_event === 'clean'
。
例如,我运行以下配置:
{
"name": "npm-test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"pretest": "node test.js",
"test": "node index.js",
"posttest": "node test.js"
},
"author": "",
"license": "ISC"
}
test.js 内容:
console.log(process.env.npm_lifecycle_event)
以及命令 npm test
的输出:
> npm-test@1.0.0 pretest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js
pretest
> npm-test@1.0.0 test /Users/bartlomiejgladys/Desktop/programming/npm-test
> node index.js
hi
> npm-test@1.0.0 posttest /Users/bartlomiejgladys/Desktop/programming/npm-test
> node test.js
posttest
关于javascript - NPM 知道脚本是否作为前/后脚本运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61066073/