javascript - NPM 知道脚本是否作为前/后脚本运行

标签 javascript node.js

假设我有这样的东西:

{
  "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/

相关文章:

javascript - Google Maps API v3 标记掉落和反弹动画

javascript - 如何在此 div 的内容中按数字(带小数)排序 div

javascript - 如何在 Node.js 中使用 JSON 对象更新 mySQL 表?

javascript - 使用nodejs在mysql中插入多个值会导致解析错误

node.js - 你如何在同一个端口上运行 express 和 socket.io

javascript - jquery整页滚动,无需插件

javascript - scrollTop 等于 0,即使 div 位于页面下方

node.js - Mongoose - findByIdAndUpdate - 不适用于 req.body

javascript - 文本区域中的 html 字符串

javascript - Keystone JS 中的验证错误