之前看了优雅的提交你的Git Commit Message文章后,项目中一直习惯使用husky
+commitlint
+lint-staged
组合来在提交代码时检测代码和提交风格.
不用说😍那是省心又省力.结果最近重新搭建项目时发现husky
更新了,并且配置有了一些变化😂,
那么就来整理下更新后husky的配置方法.
husky
在husky
更新6.0
的版本后,相关配置也发生了变化,总体来说变得更加简洁一些.
# npx husky-init
husky-init
会自动添加husky
依赖,并添加prepare
的script.
然后会发现多出来了一个.husky
目录,然后可以通过npx husky add
命令添加对应的hook
# npx husky add .husky/commit-msg "npm test"
在.husky
目录下生成对应的commit-msg
文件就是相应的husky
的hook
文件
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npm test
当执行对应的的git hook
是就会执行对应的husky hook
文件了
commitlint
通过commitlint
可以完成对提交时的commit message
检测.
安装commitlint
# yarn add @commitlint/config-conventional @commitlint/cli -D
可以在package.json
配置相关检测规则
// package.json
...
"commitlint": {
"extends": [
"@commitlint/config-conventional"
]
}
也可以将配置提取到commitlint.config.js
文件中单独配置
在extends
中指定配置文件可以来实现自定义配置
// commitlint.config.js
module.exports = {
extends: ['./commitlint.base.js', './commitlint.types.js'],
};
具体配置可以参考官方的配置文档
然后我们就可以直接添加hook
来在commit
时调用commitlint
了
# npx husky add .husky/commit-msg 'npx --no-install commitlint --edit "$1"'
lint-staged
通过lint-staged
可以在代码commit
前来执行代码质量检测,来保证代码通过检测后才可提交.
安装list-staged
# yarn add lint-staged -D
然后添加lint-staged
的相关配置,可以在package.json
中,也可以创建单独的配置文件
- lint-staged.config.js
- .lintstagedrc.json
- .lintstagedrc.yaml
- .lintstagedrc.yml
- .lintstagedrc.js
- .lintstagedrc.cjs
{
"*.ts!*.d.ts": [
"eslint --fix",
"prettier --write",
"git add ."
],
"*.vue": [
"eslint --fix",
"prettier --write",
"git add ."
],
"*.js": "eslint --cache --fix",
"*.css": "stylelint --fix"
}
按对应的文件后缀配置对应的相关代码检测就好.
最后记得来添加对应的hook
来
# npx husky add .husky/pre-commit 'npx --no-install lint-staged'
注意的是lint-staged
检测的是本地代码提交的内容,记得在代码修改后执行git add
来将修改添加到提交列表里.
commitizen
还有就是通过commitizen
来代替你的git commit
来生成格式化的提交消息
# yarn add commitizen cz-conventional-changelog -D
也可以使用带表情的cz-conventional-changelog-emoji
在package.json添加相应配置即可
"script": {
"commit": "git-cz",
},
"config": {
"commitizen": {
"path": "cz-conventional-changelog-emoji"
}
}
如果需要添加自定义的提交选项可以安装cz-customizable
来实现.
"config": {
"commitizen": { // not needed for standlone usage
"path": "node_modules/cz-customizable"
},
"cz-customizable": {
"config": "config/path/to/my/.cz-config.js"
}
}
然后按照自己的需要进行配置即可
// .cz-config.js
module.exports = {
types: [
{
value: 'feat',
name : 'feat: A new feature'
},
{
value: 'fix',
name : 'fix: A bug fix'
},
{
value: 'docs',
name : 'docs: Documentation only changes'
},
{
value: 'refactor',
name : 'refactor: A code change that neither fixes a bug nor adds a feature'
},
{
value: 'perf',
name : 'perf: A code change that improves performance'
},
{
value: 'test',
name : 'test: Add missing tests or correcting existing tests'
},
{
value: 'build',
name : 'build: Add missing tests or correcting existing tests'
},
{
value: 'revert',
name : 'revert: Revert to a commit'
}
],
allowBreakingChanges: ['feat', 'fix', 'refactor', 'perf', 'build', 'revert']
};