为什么要配置githook
昨为项目自动化监测的重要环节,由于Git 本身也具有对特定事件挂载脚本的能力(commit/push/receive...)那么通过git hook 对提交前(pre-commit)的代码做一遍检查是提高项目质量的一个重要环节。
配置gitHooks
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js}": [
"eslint --fix",
"git add"
],
"src/**/*.{ts,tsx}": [
"tslint --fix",
"git add"
],
"src/**/*.{sass,scss,css,wxss}": [
"stylelint --fix",
"git add"
]
},
上面的配置对js/ts/tsx/css 等文件做了lint监测。
坑
配置husky 操作githooks 脚本。
首先项目开始时使用git init 初始化项目文件内后项目文件内会生成.git文件夹。钩子脚本都在里面 .git/hooks 。此时里面的脚本都是.sample 结尾的例子文件,执行后无效果。
直接npm i husky -D --save 操作了一波。最后跑了好几遍发现不管用。然后逐一排查问题
- 初始化架构有没有hooks文件夹
- 生成项目的时候是否hooks文件夹覆盖了
- hooks文件夹有读写权限
定位到最后发现,安装husky后,hooks文件夹下仍然是.sample的模板。是husky版本的问题。4~5版本在安装时。不会重写windows环境下的.git/hooks 文件夹。
husky 坑点
1.windows 环境下 yarn 安装 2.windows 环境下 用cnpm 镜像安装
以上情况都会出问题。
最后换了v3.1.0 版本才最后解决了这个问题。
正常安装的husky 会在hooks文件夹用将 githook.sample 模板文件的同名脚本覆盖掉。如下:
#!/bin/sh
# husky
# Hook created by Husky
# Version: 3.1.0
# At: 2021/1/7 下午4:42:08
# See: https://github.com/typicode/husky#readme
# From
# Directory: undefined
# Homepage: https://github.com/typicode/husky#readme
scriptPath="node_modules/husky/run.js"
hookName=`basename "$0"`
gitParams="$*"
debug() {
if [ "${HUSKY_DEBUG}" = "true" ] || [ "${HUSKY_DEBUG}" = "1" ]; then
echo "husky:debug $1"
fi
}
debug "husky v3.1.0 (created at 2021/1/7 下午4:42:08)"
debug "$hookName hook started"
debug "Current working directory is '`pwd`'"
if [ "${HUSKY_SKIP_HOOKS}" = "true" ] || [ "${HUSKY_SKIP_HOOKS}" = "1" ]; then
debug "HUSKY_SKIP_HOOKS is set to ${HUSKY_SKIP_HOOKS}, skipping hook"
exit 0
fi
if [ "${HUSKY_USE_YARN}" = "true" ] || [ "${HUSKY_USE_YARN}" = "1" ]; then
debug "Calling husky through Yarn"
yarn husky-run $hookName "$gitParams"
else
if [ -f "$scriptPath" ]; then
# if [ -t 1 ]; then
# exec < /dev/tty
# fi
if [ -f ~/.huskyrc ]; then
debug "Sourcing '~/.huskyrc'"
. ~/.huskyrc
fi
node "$scriptPath" $hookName "$gitParams"
else
echo "Can't find Husky, skipping $hookName hook"
echo "You can reinstall it using 'npm install husky --save-dev' or delete this hook"
fi
fi
最后建议使用husky时在package.json 里把husky版本锁定。