eslint + pre-commit

eslint + pre-commit

上一篇文章,把eslint引入了项目中做代码规范检查。 但是在团队协作中,还是可能有同事误提交不合规范的代码,于是有了eslint + pre-commit 的方案。

pre-commit是git的钩子,顾名思义就是在提交前运行,所以一般用于代码检查、单元测试。git还有其他钩子,比如prepare-commit-msg、pre-push等,具体可查看git官网

1、安装pre-commit

npm install -D pre-commit

2、配置package.json

配置项如下:

"scripts": {
    "start": "cross-env NODE_ENV=development node build/dev.js",
    "build": "cross-env NODE_ENV=production node build/prod.js",
    "lint": "eslint --ext .jsx,.js src/  --fix ./src --cache"
 },
 "pre-commit": [
    "lint"
 ],

就这样,就实现了在每次 commit 之前进行代码检查。我们可以试一下 在有不合规范代码的情况下 commit,出现如下:

7:12  error  Parsing error: Unexpected token

   5 | 
   6 | export class About extends Component {
>  7 |     console.log(111);
     |            ^
   8 |   
   9 |   render () {
  10 |     return (

✖ 1 problem (1 error, 0 warnings)

pre-commit: 
pre-commit: We've failed to pass the specified git pre-commit hooks as the `lint`
pre-commit: hook returned an exit code (1). If you're feeling adventurous you can
pre-commit: skip the git pre-commit hooks by adding the following flags to your commit:
pre-commit: 
pre-commit:   git commit -n (or --no-verify)
pre-commit: 
pre-commit: This is ill-advised since the commit is broken.

相关推荐