需求: 爲了提升代碼規範, 咱們須要使開發者去掉一些多餘的代碼, 如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等代碼. 若是有, 會提示錯誤(以下)