typescript-eslint/naming-convention规则未生效?配置排查求助
ESLint 命名规则未检测大写函数名错误
我配置了@typescript-eslint/naming-convention规则,期望全大写命名的函数被检测为错误,但实际并未生效。以下是我的配置和测试代码:
我的.eslintrc.js配置:
module.exports = { root: true, parser: '@typescript-eslint/parser', parserOptions: { ecmaVersion: 2020, sourceType: 'module', project: './tsconfig.json', tsconfigRootDir: __dirname, createDefaultProgram: true, }, plugins: ['@typescript-eslint'], settings: { 'import/resolver': { node: {}, typescript: {}, }, 'import/parsers': { '@typescript-eslint/parser': ['.ts', '.tsx'], }, }, rules: { // 命名规则配置 '@typescript-eslint/naming-convention': [ 'error', { selector: 'default', format: ['camelCase'], }, // 解构变量不强制格式 { selector: 'variable', modifiers: ['destructured'], format: null, }, // 函数类型的const变量允许驼峰和大驼峰 { selector: 'variable', types: ['function'], modifiers: ['const'], format: ['camelCase', 'PascalCase'], }, // 普通const变量允许全大写和驼峰 { selector: 'variable', modifiers: ['const'], format: ['UPPER_CASE', 'camelCase'], }, // 函数允许驼峰和大驼峰 { selector: 'function', format: ['camelCase', 'PascalCase'], }, // 类型定义使用大驼峰 { selector: 'typeLike', format: ['PascalCase'], }, // 枚举成员使用全大写 { selector: 'enumMember', format: ['UPPER_CASE'], }, // 忽略需要引号的属性 { selector: [ 'classProperty', 'objectLiteralProperty', 'typeProperty', 'classMethod', 'objectLiteralMethod', 'typeMethod', 'accessor', 'enumMember', ], format: null, modifiers: ['requiresQuotes'], }, ], }, };
测试代码:
function FUNCTION1() { // 这个函数名应该报错,但实际没有 } const FUNCTION2 = () => {}; // 这个也应该报错,但实际没有 const function3 = () => {}; // 这个是正确的 function4() {} // 这个也是正确的
请问我的配置哪里有问题?
问题分析与修复
1. function FUNCTION1() 未报错的原因
你的规则中已经明确限制函数名只能使用camelCase或PascalCase,全大写的FUNCTION1不符合规则却未报错,大概率是文件类型不匹配:
- 配置里
import/parsers仅指定@typescript-eslint/parser处理.ts/.tsx文件,如果测试文件是.js格式,ESLint会使用默认解析器,@typescript-eslint的规则不会生效。 - 解决:如果需要处理
.js文件,在import/parsers中添加.js:'import/parsers': { '@typescript-eslint/parser': ['.ts', '.tsx', '.js', '.jsx'], },
2. const FUNCTION2 = () => {} 未报错的原因
这条代码未触发错误是规则匹配顺序+类型解析问题共同导致的:
- 规则顺序中,
variable + const规则在variable + types:['function'] + const规则之后,但如果ESLint无法获取变量的类型信息(比如tsconfig.json未包含该文件、路径配置错误),types:['function']的条件就不满足,代码会匹配到后面的variable + const规则——而该规则允许UPPER_CASE,因此不会报错。 - 即使ESLint能解析类型,若想彻底禁止函数类型的变量使用全大写,可以调整规则,排除函数类型的普通const变量:
// 修改普通const变量的规则,排除函数类型 { selector: 'variable', modifiers: ['const'], types: ['!function'], // 排除函数类型的const变量 format: ['UPPER_CASE', 'camelCase'], }, - 另外,确保
tsconfig.json的include字段包含你的测试文件,让ESLint能正确获取类型信息,这样variable + types:['function'] + const规则才能正常触发。
最终调整后的关键规则片段
'@typescript-eslint/naming-convention': [ 'error', // ...其他规则保持不变 // 函数类型的const变量允许驼峰和大驼峰 { selector: 'variable', types: ['function'], modifiers: ['const'], format: ['camelCase', 'PascalCase'], }, // 普通const变量允许全大写和驼峰(排除函数类型) { selector: 'variable', modifiers: ['const'], types: ['!function'], format: ['UPPER_CASE', 'camelCase'], }, // ...其他规则保持不变 ],
内容的提问来源于stack exchange,提问作者danikaze
相关产品推荐
相关产品推荐

