良好的代码规范有助于项目的维护和新人的快速上手。前段时间,把eslint引入了项目中作静态代码检查。 一下把全部的代码都改造是不可能,要改的地方太多,并且要保证后来提交代码的质量。因而有了eslint + pre-commit 的结合。
pre-commit是git的钩子,顾名思义就是在提交前运行,因此通常用于代码检查、单元测试。git还有其余钩子,好比prepare-commit-msg、pre-push等,具体可查看git官网。git 钩子目录在.git/hooks下(以下图):node
git-hooks.pnggit
上图这些文件都是对应钩子的示例脚本,.sample后缀都是出于未启动状态。对应的钩子要生效,把.sample去掉。示例都是用shell脚本写的。那若是想用js写怎么办呢?须要借助pre-commit库:github
npm install pre-commit --save-dev
// package.json "scripts": { "lint": "eslint src --ext .js --cache --fix", }, "pre-commit": [ "lint", ]
上面配置会保证eslint在提交时会校验src目录下的js文件。
那若是要动态获取提交的代码进行校验呢?shell
// 获取修改后的js文件 git diff HEAD --name-only| grep .js$
package.json文件可改成:npm
// package.json "scripts": { "lint": "eslint src --ext .js --cache --fix", "pre-lint": "node check.js" }, "pre-commit": [ "pre-lint", ]
在check.js中须要调用eslint的Node.js API,详情可看eslint官网。如下是我在项目中的例子,可做为参考:json
// check.js const exec = require('child_process').exec const CLIEngine = require('eslint').CLIEngine const cli = new CLIEngine({}) function getErrorLevel(number) { switch (number) { case 2: return 'error' case 1: return 'warn' default: } return 'undefined' } let pass = 0 exec('git diff --cached --name-only| grep .js$', (error, stdout) => { if (stdout.length) { const array = stdout.split('\n') array.pop() const results = cli.executeOnFiles(array).results let errorCount = 0 let warningCount = 0 results.forEach((result) => { errorCount += result.errorCount warningCount += result.warningCount if (result.messages.length > 0) { console.log('\n') console.log(result.filePath) result.messages.forEach((obj) => { const level = getErrorLevel(obj.severity) console.log(` ${obj.line}:${obj.column} ${level} ${obj.message} ${obj.ruleId}`) pass = 1 }) } }) if (warningCount > 0 || errorCount > 0) { console.log(`\n ${errorCount + warningCount} problems (${errorCount} ${'errors'} ${warningCount} warnings)`) } process.exit(pass) } if (error !== null) { console.log(`exec error: ${error}`) } })
做者:du_4c0c
连接:https://www.jianshu.com/p/072a96633479
来源:简书
简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。api