静态代码检查:获取eslint/typescript错误数和错误详情

2,290 阅读1分钟

在进行项目到typescripteslint的迁移时会遇到很多错误,并且也不能一下修改完(笔者使用的是babel-preset-typescript, 即使有错误也能编译通过),需要排期慢慢修改完,在这个过程中需要防止新增代码增加错误,那么就需要监控错误情况,一个办法是通过husky+lint-staged的组合在commit时禁止提交,但是这个是不可靠的,完全可以绕过这个检查提交,那么就需要在CI这个环节进行检查。如何获取typescripteslint的错误情况呢?

首先使用命令行获取错误信息:

package.json

{
  "scripts": {
    "lint:eslint": "eslint . --ext '.js,.ts' --no-color > eslint-analyze.log || exit 0",
    "lint:typescript": "tsc --pretty false --skipLibCheck true  -p  . > typescript-analyze.log || exit 0"
  }
}

exit 0的原因:eslint "Exit status 1"

结果是这样的: eslint-analyze.log

/paht/to.ts
  31:28  error  'aaa' was used before it was defined  @typescript-eslint/no-use-before-define
  
✖ 1 problems (1 errors, 0 warnings)

typescript-analyze.log

path/to.ts(46,5): error TS2571: Object is of type 'unknown'.
然后提取错误数

eslint:

// ✖ 1 problems (1 errors, 0 warnings)
const RESULT_REG = /(\d+) problems \((\d+) errors, (\d+) warnings\)/;

const log = fs.readFileSync(path.resolve('eslint-analyze.log')).toString();
const resultLine = log.split('\n').find(line => RESULT_REG.test(line));
const matchedResult = resultLine.match(RESULT_REG);
const [, totalCount, errorCount, warningCount] = matchedResult;

typescript:

// 每个错误格式都是固定的
const ERROR_REG = /error TS/g;

const log = fs.readFileSync(path.resolve('eslint-analyze.log')).toString();
const errorCount = log.match(ERROR_REG).length;

这样我们得到了错误数和错误详情,下一步就可以集成到CI里了,通知给小伙伴了:使用 nodejs 给企业微信发消息