上一篇文章,把eslint引入了项目中作代码规范检查。 可是在团队协做中,仍是可能有同事误提交不合规范的代码,因而有了eslint + pre-commit 的方案。node
pre-commit是git的钩子,顾名思义就是在提交前运行,因此通常用于代码检查、单元测试。git还有其余钩子,好比prepare-commit-msg、pre-push等,具体可查看git官网。git
npm install -D pre-commit
配置项以下:npm
"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,出现以下:json
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.