[关闭]
@pspgbhu 2017-06-06T02:44:30.000000Z 字数 765 阅读 1464

npm script 摘要

nodejs


npm scripts 使用指南 -- 阮一峰 http://www.ruanyifeng.com/blog/2016/10/npm_scripts.html

1. 钩子

npm 脚本有pre和post两个钩子。举例来说,build脚本命令的钩子就是prebuild和postbuild。

  1. "prebuild": "echo I run before the build script",
  2. "build": "cross-env NODE_ENV=production webpack",
  3. "postbuild": "echo I run after the build script"

用户执行npm run build的时候,会自动按照下面的顺序执行。

  1. npm run prebuild && npm run build && npm run postbuild

因此,可以在这两个钩子里面,完成一些准备工作和清理工作。下面是一个例子。

2. npm_lifecycle_event 环境变量

npm 提供一个npm_lifecycle_event变量,返回当前正在运行的脚本名称,比如pretest、test、posttest等等。所以,可以利用这个变量,在同一个脚本文件里面,为不同的npm scripts命令编写代码。请看下面的例子。

  1. const TARGET = process.env.npm_lifecycle_event;
  2. if (TARGET === 'test') {
  3. console.log(`Running the test task!`);
  4. }
  5. if (TARGET === 'pretest') {
  6. console.log(`Running the pretest task!`);
  7. }
  8. if (TARGET === 'posttest') {
  9. console.log(`Running the posttest task!`);
  10. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注