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:12errorParsing 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.