Git 自己除了代码版本管理以外,还提供了 Git Hooks 钩子机制,它可以让咱们在 commit、push 以前(后)执行一些自定义的操做。javascript
在每一个 Git 项目根目录下,都会有一个隐藏的 .git 目录,其中 hooks 目录中提供了许多默认的钩子脚本,去掉其默认的 .sample 后缀便可在对应的步骤执行该脚本文件。css
npm install -D husky
复制代码
安装 husky 以后,能够看到 .git/hooks 目录中文件的变化:html
其中 pre-*
为某一操做以前运行的脚本,post-*
为某一操做以后运行的脚本。vue
在 package.json 中加入以下配置:java
// package.json
{
"husky": {
"hooks": {
"pre-commit": "npm run lint",
"pre-push": "npm test",
"...": "..."
}
},
"...": "..."
}
复制代码
从 1.0.0
开始,husky 能够配置为 .huskyrc
,.huskyrc.json
,.huskyrc.yaml
,huskyrc.yml
,.huskyrc.js
或husky.config.js
文件。node
// .huskyrc
{
"hooks": {
"pre-commit": "npm run lint"
}
}
复制代码
如今,每次 commit 以前都会运行 npm run lint
命令,若是存在错误(error),将不能提交代码。PS:若是只是警告(warning),会有相应的提示信息,可是是能够成功提交的。git
上一步中,每次提交前都会检查全部代码。在大型项目中这会使得提交速度很慢。并且,这可能会致使别人的代码错误使得咱们的修改没法提交。如今咱们使用 lint-staged 来解决这个问题,每一个团队成员提交的时候,只检查当次改动的文件。github
npm install -D lint-staged
复制代码
// package.json
{
"lint-staged": {
"*.vue": "vue-cli-service lint",
"*.js": "eslint",
"*.less": "stylelint",
"*.css": "stylelint",
"*.scss": "stylelint",
"*.md": "markdownlint"
},
"...": "..."
}
复制代码
// .huskyrc
{
"hooks": {
"pre-commit": "lint-staged"
}
}
复制代码
如今,咱们每次提交时都只会检查咱们本身改动的文件,不再用去给别人修复错误了😁vue-cli
规范的 commit message 更有利于阅读和维护,有助于团队的 code review,提升团队工做效率。同时方便咱们生成 Change log。推荐使用 Angular 规范。shell
npm install -D @commitlint/config-conventional @commitlint/cli
复制代码
// .huskyrc
{
"husky": {
"hooks": {
"pre-commit": "lint-staged",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
复制代码
// commitlint.config.js
module.exports = {
extends: ['@commitlint/config-conventional']
}
复制代码
当咱们的 commit message 不符合规范时,将没法进行提交❌
咱们修改一下 commit message,使其符合 Angular 规范,再次提交✅
# 全局安装
npm install -g commitizen
# 项目级安装
npm install -D commitizen cz-conventional-changelog
复制代码
若是是全局安装,在项目目录下,运行下面的命令,使其支持 Angular 的 Commit message 格式。
commitizen init cz-conventional-changelog --save --save-exact
复制代码
若是是项目级安装,则需在 package.json
中加入下面的配置:
{
"script": {
"...": "...",
"commit": "git-cz"
},
"config": {
"commitizen": {
"path": "node_modules/cz-conventional-changelog"
}
},
"...": "..."
}
复制代码
如今,在须要使用git commit
命令的地方,改成使用git cz
(全局安装时)或者npm run commit
(项目级安装时)命令。而后在命令行中经过答题方式生成规范的 commit message。翻译以下:
Select the type of change that you're committing: (Use arrow keys)
选择要提交的更改类型:(经过上下箭头键)
What is the scope of this change (e.g. component or file name): (press enter to skip)
说明这次提交的影响范围(好比:视图层或者某个文件名)(回车跳过)
Write a short, imperative tense description of the change (max 95 chars):
简短描述
Provide a longer description of the change: (press enter to skip)
详细描述(回车跳过)
Are there any breaking changes? (y/N)
有没有与上个版本不兼容的更改?
Does this change affect any open issues? (y/N)
这次提交是否针对某个 issues?
若是咱们的 commit message 都符合上面的规范,那么在项目发布时就能够自动生成 Change log 文档。
npm install -D conventional-changelog-cli
复制代码
// package.json
{
"scripts": {
"...": "..."
"changelog": "conventional-changelog -p angular -i ./你的自定义路径/CHANGELOG.md -s -r 0"
},
"...": "..."
}
复制代码
运行npm run change log
便可生成 CHANGELOG.md 文档。