TypeScript项目ESLint规则适配问题及自定义规则报错求助
版本信息
| package | version |
|---|---|
| node | v11.15.0 |
| typescript | ~3.1.1 |
| @typescript-eslint/eslint-plugin | 4.0.0 |
| eslint | 7.0.0 |
| @typescript-eslint/parser | 4.0.0 |
问题描述
需要在JavaScript和TypeScript项目中检测三类代码问题:max-depth(嵌套深度超限)、max-lines-per-function(单函数行数超限)、complexity(代码复杂度超限)。发现typescript-eslint无对应规则,借助ChatGPT编写了自定义规则文件max-nesting-depth.ts,但运行npx eslint .时触发SyntaxError错误。
补充(2023年10月24日):单独启用ESLint原生max-lines-per-function规则时,仅能检测JavaScript文件的问题,TypeScript文件中大量超过20行的函数未被识别。需解决自定义规则报错、原生规则不检测TS文件的问题。
解决方案
一、修复原生ESLint规则不检测TS文件的问题
- 完善ESLint配置,确保解析TS语法
在.eslintrc.js中指定TS解析器及项目配置,同时明确规则作用范围:
module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { project: './tsconfig.json', // 关联TS配置文件,保证解析器正确识别TS语法 ecmaVersion: 2020, sourceType: 'module' }, plugins: ['@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended' ], rules: { // 启用原生规则并设置阈值 'max-depth': ['error', 4], 'max-lines-per-function': ['error', { max: 20, skipBlankLines: true, skipComments: true }], 'complexity': ['error', 10] }, // 明确指定TS文件的规则覆盖 overrides: [ { files: ['*.ts', '*.tsx'], env: { es6: true } } ] };
- 运行ESLint时指定文件扩展名
执行命令时明确包含TS文件,避免ESLint默认只处理JS:
npx eslint . --ext .js,.ts
二、解决自定义规则的SyntaxError问题
- 遵循ESLint规则编写规范
自定义规则需使用CommonJS格式(适配Node v11),并兼容TS AST节点类型。以max-nesting-depth为例,正确结构如下:
// max-nesting-depth.js(需将TS编译为JS后使用) module.exports = { meta: { type: 'suggestion', schema: [{ type: 'integer', minimum: 0, default: 4 }], messages: { exceed: '嵌套深度超过最大值{{max}}(当前为{{depth}})' } }, create(context) { const max = context.options[0] || 4; let currentDepth = 0; const increment = node => { currentDepth++; if (currentDepth > max) { context.report({ node, messageId: 'exceed', data: { max, depth: currentDepth } }); } }; const decrement = () => currentDepth--; // 监听所有会增加嵌套深度的节点类型 const nestingNodes = [ 'IfStatement', 'ForStatement', 'WhileStatement', 'SwitchCase', 'TryStatement', 'CatchClause', 'FunctionDeclaration', 'ArrowFunctionExpression' ]; const listeners = {}; nestingNodes.forEach(type => { listeners[`${type}:enter`] = increment; listeners[`${type}:exit`] = decrement; }); return listeners; } };
- 正确引入自定义规则
在.eslintrc.js中配置规则路径:
module.exports = { // ...其他配置 plugins: [ 'custom' // 自定义插件标识 ], rules: { 'custom/max-nesting-depth': ['error', 4] }, settings: { 'eslint-plugin-custom': { path: './rules' // 自定义规则文件所在目录 } } };
- 编译TS格式的自定义规则
Node v11无法直接运行TS文件,需先编译为JS:
tsc max-nesting-depth.ts
三、替代方案:使用@typescript-eslint兼容规则
@typescript-eslint已提供原生规则的TS兼容支持,部分规则需开启parserOptions.project才能生效。此外,可直接使用其内置复杂度规则:
rules: { '@typescript-eslint/complexity': ['error', 10], 'max-depth': ['error', 4], 'max-lines-per-function': ['error', 20] }
内容的提问来源于stack exchange,提问作者maq5ud
相关产品推荐
相关产品推荐

