如何配置@typescript-eslint/naming-convention适配自定义变量命名规则?
解决ESLint @typescript-eslint/naming-convention规则兼容自定义命名格式的问题
核心方案
借助@typescript-eslint/naming-convention规则的filter与正则匹配能力,针对指定section前缀的变量放行自定义命名格式,无需逐个添加禁用注释。
具体配置步骤
假设你的section可选值为home、profile、settings,在ESLint配置文件(如.eslintrc.js)中修改规则如下:
配置示例
module.exports = { // 其他配置项... rules: { '@typescript-eslint/naming-convention': [ 'error', // 保留原有基础命名规则 { selector: 'variable', format: ['camelCase', 'PascalCase', 'UPPER_CASE'], }, // 新增规则:允许指定section前缀的自定义命名 { selector: 'variable', filter: { regex: '^(home|profile|settings)_.*_[A-Z][a-zA-Z0-9]*$', match: true, }, format: null, // 关闭默认格式检查 custom: { regex: '^(home|profile|settings)_.*_[A-Z][a-zA-Z0-9]*$', match: true, }, }, // 函数、类等其他规则保持原有配置... ], }, };
配置说明
- 正则
^(home|profile|settings):替换成你实际的section可选值,多值用|分隔,限定允许的前缀范围。 _.*_:匹配中间的下划线分隔部分(比如示例中的page)。[A-Z][a-zA-Z0-9]*:匹配结尾的驼峰式命名(比如示例中的objectTitle)。format: null:告知ESLint不对这类变量强制执行默认命名格式,完全以自定义正则为准。
调整验证
- 将正则中的section值替换为你项目的实际可选值。
- 重启ESLint服务或重新执行代码检查,确认
section_page_objectTitle格式的变量不再触发警告。
内容的提问来源于stack exchange,提问作者Razmodius
相关产品推荐
相关产品推荐

