为前端项目添加ESLint pre-commit git hook

为统一前端代码规范并通过工具强制实施。可以通过添加为git仓库添加pre-commit hook添加eslint对代码的检查。

Git Hooks

每个git仓库在其目录下都有一个.git/hooks目录,里面放了一些shell脚本,作为git命令的hook:

applypatch-msg.sample
commit-msg.sample
fsmonitor-watchman.sample
post-update.sample
pre-applypatch.sample
pre-commit
pre-push.sample
pre-rebase.sample
pre-receive.sample
prepare-commit-msg.sample
update.sample

先安装ESLint

npm i --save-dev eslint
yarn add -D eslint

生成.eslintrc.json

node_modules/.bin/eslint --init

开启pre-commit hook

将pre-commit.sample去掉后缀,并改写为:

#!/bin/sh

STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".jsx\{0,1\}$")
ESLINT="$(git rev-parse --show-toplevel)/node_modules/.bin/eslint"

if [[ "$STAGED_FILES" = "" ]]; then
  exit 0
fi

PASS=true

printf "\n检查JavaScript代码中...:\n"

# Check for eslint
if [[ ! -x "$ESLINT" ]]; then
  printf "\t\033[41m请先安装ESlint: npm i --save-dev eslint"
  exit 1
fi

for FILE in $STAGED_FILES
do
  "$ESLINT" "$FILE"

  if [[ "$?" == 0 ]]; then
    printf "\t\033[32mESLint通过: $FILE\033[0m"
  else
    printf "\t\033[41mESLint失败: $FILE\033[0m"
    PASS=false
  fi
done

printf "\nDone!\n"

if ! $PASS; then
  echo "\033[41m提交失败:\033[0m 请修复ESLint提示的问题再提交.\n"
  exit 1
else
  echo "\033[42m提交成功\033[0m\n"
fi

exit $?

 

index.js只包含一行代码:

console.log(1)

修复:

/*eslint no-console: ["error", { allow: ["log", "warn", "error"] }] */
console.log(1);

lint-staged

通过 npm i --save-dev lint-staged并在package.json中设置gitHooks 来设置在pre-commit时做lint检查:

"gitHooks": {
  "pre-commit": "lint-staged"
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top