You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置@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不对这类变量强制执行默认命名格式,完全以自定义正则为准。

调整验证

  1. 将正则中的section值替换为你项目的实际可选值。
  2. 重启ESLint服务或重新执行代码检查,确认section_page_objectTitle格式的变量不再触发警告。

内容的提问来源于stack exchange,提问作者Razmodius

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:25:41