需求: 为了提升代码规范, 咱们须要使开发者去掉一些多余的代码, 如console, alert, debugger等, 会影响到其余开发者.
1. 实现思路: 使用git 的钩子函数, 在commit前进行代码检查.
2. 实现步骤;
(1)
```npm install pre-commit --save-dev```
```npm instal husky --save-dev```
复制代码
(2) 在package.json中添加执行代码
(3) 须要在项目根目录下, 新建hooks/check-keyword.sh, 代码以下
#!/bin/bash
red=`tput setaf 1`
green=`tput setaf 2`
reset=`tput sgr0`
echo "${green}start checking keyword${reset}"
for FILE in `git diff --name-only --cached`; do
if [[ $FILE == *".sh"* ]] || [[ $FILE == *"iconfont.js"* || $FILE == *"ExamplePage"* || $FILE == *"min.js"* || $FILE == *"vendor/*"* ]] ; then
echo $FILE
continue
fi
grep 'TODO:\|debugger\|console.log\|alert(' $FILE 2>&1 >/dev/null
if [ $? -eq 0 ]; then
echo $FILE '包含,TODO: or debugger or console.log,请删除后再提交'
exit 1
fi
done
exit
复制代码
(4) 而后就大功告成啦. Commit 时 会执行check-keyword.sh这个脚本,这个脚本会检测 console, alert, debugger等代码. 若是有, 会提示错误(以下)