@pspgbhu
2017-06-06T02:44:30.000000Z
字数 765
阅读 1465
nodejs
npm scripts 使用指南 -- 阮一峰 http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html
npm 脚本有pre和post两个钩子。举例来说,build脚本命令的钩子就是prebuild和postbuild。
"prebuild": "echo I run before the build script",
"build": "cross-env NODE_ENV=production webpack",
"postbuild": "echo I run after the build script"
用户执行npm run build的时候,会自动按照下面的顺序执行。
npm run prebuild && npm run build && npm run postbuild
因此,可以在这两个钩子里面,完成一些准备工作和清理工作。下面是一个例子。
npm 提供一个npm_lifecycle_event变量,返回当前正在运行的脚本名称,比如pretest、test、posttest等等。所以,可以利用这个变量,在同一个脚本文件里面,为不同的npm scripts命令编写代码。请看下面的例子。
const TARGET = process.env.npm_lifecycle_event;
if (TARGET === 'test') {
console.log(`Running the test task!`);
}
if (TARGET === 'pretest') {
console.log(`Running the pretest task!`);
}
if (TARGET === 'posttest') {
console.log(`Running the posttest task!`);
}