如何通过运行`npm install`来检测`prepublish`脚本的执行时间
https://docs.npmjs.com/misc/scripts
预发布:在包发布之前运行。 (也可以在没有任何参数的情况下在本地npm上运行。)
我希望我的脚本只在用户执行npm publish
执行。 但是,如果用户运行“npm install”,NPM将执行“prepublish”脚本。
我想到的唯一方法是使用NPM内部的ENVvariables:
// NPM will run prepublish script after `npm install` (https://docs.npmjs.com/misc/scripts) // This ensures that when script is executed using `npm *` it is run only when the command is `npm publish`. if (process.env.npm_config_argv) { let npmConfigArgv; npmConfigArgv = JSON.parse(process.env.npm_config_argv); if (npmConfigArgv.original[0] !== 'publish') { console.log('`bundle-dependencies prepublish` will not execute. It appears that `prepublish` script has been run by `npm install`.'); return; } }
看起来,NPM将原始命令存储在process.env.npm_config_argv
variables中。
如果你想知道,每个NPM脚本正在不同的过程中运行。 因此,在preinstall
脚本中设置自定义ENVvariables等操作不起作用。
另一个解决scheme也适用于我(再次从这个线程 )是使用像以下prepublish.sh
脚本:
get_json_val() { python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1))"; } get_npm_command() { local temp=$(echo $npm_config_argv | get_json_val "['original'][0]") echo "$temp" | tr -dc "[:alnum:]" } if [ $(get_npm_command) != "publish" ]; then echo "Skipping prepublish script" exit 0 fi # else echo "prepublish called" # prepublish logic follows: # ...
所以如果你的package.json
文件是:
{ "name": "foo", "version": "0.0.1", "description": "", "main": "lib/foo.js", "scripts": { "prepublish": "./prepublish.sh" }, "dependencies": { "lodash": "^4.10.0" } }
…然后运行npm install
将只安装依赖关系, 只有当用户键入npm run publish
时才会调用prepublish
目标。
另一种方法是使用in-publish
包(在这个线程中再次提到)。 把它放在你的开发依赖中,然后在你的package.json
有这样的东西:
"prepublish": "(in-publish && npm run clean && flow check && npm run test && npm run build) || not-in-publish"
从npm@4.0.0开始 , prepublish
脚本现已被弃用 。 要在npm publish
和npm install
上都运行一个脚本(没有参数),你应该用prepare
来替代。
要仅在npm publish
上运行脚本,您应该使用prepublishOnly
。