也许你不知道的npm-scripts

前言

昨天发了一篇文章《记一次gitHook带来的思考🤔》,发现npminstalluninstall的时候能够执行脚本,@羽叶丶大佬评论说,能够继续思考下 为什么装包时能够运行脚本命令。因而乎今天就去看了一下昨天的主角yorkie,再它的package.json中发现了线索vue

{
  "scripts": {
    "install": "node bin/install.js",
    "uninstall": "node bin/uninstall.js"
  }
}
复制代码

开始思考

scripts咱们应该都知道,能够使用npm run xxx来帮助咱们完成一些事情。从昨天的发现到今天的探索来看,scripts颇有可能还充当着生命周期的角色。开始查阅npm-scripts文档,看到的结果大吃一惊。原来咱们熟知和常常使用的npm run xxx在文档中成为"另外,能够经过这种方式执行任意脚本"。下面看一下也许你不知道的npm-scripts:node

scripts的属性

生命周期scripts

  • prepublish:在打包和发布包以前运行,在npm install没有任何参数的本地运行。
  • prepare:在打包和发布包以前运行,在本地npm install:没有任何参数,以及安装git依赖项时运行。这是在以后运行prepublish,可是以前prepublishOnly
  • prepublishOnly:仅在准备和打包以前运行npm publish
  • prepack:前运行压缩包(npm packnpm publish并安装git的依赖时)
  • postpack:在生成压缩包并移动到其最终目的地以后运行。
  • publish postpublish:发布包后运行
  • preinstall:包安装以前运行
  • install postinstall:包安装后运行。默认:node-gyp rebuild,若是binding.gyp包的根目录中有一个文件而您还没有定义本身的脚本installpreinstall脚本,npm将默认install使用node-gyp进行编译。
  • preuninstall uninstall:在包卸载以前运行。
  • postuninstall:在包卸载以后运行。
  • preversion:在碰撞包版本以前运行。
  • version:碰撞包版本以后,但提交以前运行。
  • postversion:碰撞包版本以后,提交以后运行。

主动调用

  • pretest test posttest:由npm test命令运行。
  • prestop stop poststop:由npm stop命令运行。
  • prestart start poststart:由npm start命令运行。默认:node server.js
  • prerestart restart postrestart:按npm restart命令运行。注意:npm restart 若是没有restart提供脚本,将运行中止和启动脚本。 -preshrinkwrap shrinkwrap postshrinkwrap:由npm shrinkwrap命令运行。

其余发现

神秘的.bin

你可能发现有这样一个目录node_modules/.bin,在里面有webpack vue-cli-service这些常见的文件,为何会有呢?跟上面所说的scripts有必定关系webpack

运行npm start来执行脚本,在npm install时,脚本会导出到node_modules/.bin目录中。git

好比node_modules/.bin中存在脚本vue-cli-servicegithub

{
  "scripts": {
    "serve": "vue-cli-service serve --open",
  }
}
复制代码

package变量

好比 package.json中存在web

{
  "name": "test"
}

process.env.npm_package_name // 值为test
复制代码

说到这,想到一个问题,yorkie要求咱们在package.json中填写gitHooks字段,是否是经过这种方式获取的呢?看了一下源码并非。vue-cli

const pkg = fs.readFileSync(path.join(cwd, 'package.json'))
const hooks = JSON.parse(pkg).gitHooks
复制代码

钩子脚本

git拥有钩子脚本目录为.git/hooksnpm也有钩子脚本node_modules/.hooks/{eventname}其中evennamescripts字段中的。在这定义的hook将会运用到项目中全部的包。npm

最后的话

但愿你们多多指教,有什么问题欢迎评论区见,在接受批评中共同成长,共同进步。json

参考资料

相关文章
相关标签/搜索