使用pre-commit实现提交前代码检测

很多同事在提交代码前并不注意es-lint/ts-lint的代码检测结果,已经提示警告但是依然提交了代码,结果就会给别人带来很多困扰,遇见这种情况,可以使用pre-commit实现在提交前对代码执行检测,如果存在问题则拒绝提交。

首先,安装pre-commit :

1
npm install pre-commit --save-dev

我使用的是ts-lint,所以安装后添加script:

1
2
3
4
"scripts": {
"lint": "tslint --project ./tsconfig.json --exclude *.js"
...
}

然后就可以在package.json中添加pre-commit时需要执行的script:

1
2
3
"pre-commit": [
"lint"
]

这时如果存在检测不通过的代码,则会有如下提示:

1
2
3
4
5
6
7
8
9
10
11
ERROR: /src/models/user.model.ts[13, 3]: The class method 'convert' must be marked either 'private', 'public', or 'protected'
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 (2). 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.
pre-commit:

这样就可以确保,提交的代码检测通过,也比直接修改.git下的hooks方便多了