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

如何为Angular项目配置ESLint规则支持protected readonly枚举的PascalCase命名

Angular ESLint规则配置:兼容Enum开头的只读保护类属性命名

问题背景

我开发Angular项目时,已通过ESLint配置规则,要求带有protected readonly修饰符的类属性必须采用strictCamelCase命名,配置如下:

{
    "selector": ["classProperty"],
    "format": ["strictCamelCase"],
    "leadingUnderscore": "forbid",
    "trailingUnderscore": "forbid",
    "modifiers": ["protected", "readonly"]
}

项目中存在EnumButtonSize这类枚举,我需要将其声明为protected readonly EnumButtonSize = EnumButtonSize;(添加protected修饰符是为了避免变量出现在Storybook文档中,也可通过添加@internal装饰器注释替代),并在模板中使用:

<my-button [buttonSize]="EnumButtonSize.LARGE">

我尝试新增ESLint规则,允许这类以Enum开头的枚举采用StrictPascalCase命名,但以下配置未生效:

{
   "selector": ["classProperty"],
   "format": ["StrictPascalCase"],
   "leadingUnderscore": "forbid",
   "trailingUnderscore": "forbid",
   "modifiers": ["protected", "readonly"],
   "filter": {
      "regex": "^Enum.*",
      "match": true
   }
},

解决方案

方案1:调整规则匹配顺序并优化正则

ESLint的命名规则按配置顺序匹配,符合条件的规则会优先生效。需将Enum专属规则放在通用规则之前,同时优化正则确保匹配精准:

[
  {
     "selector": ["classProperty"],
     "format": ["StrictPascalCase"],
     "leadingUnderscore": "forbid",
     "trailingUnderscore": "forbid",
     "modifiers": ["protected", "readonly"],
     "filter": {
        "regex": "^Enum[A-Z].*",
        "match": true
     }
  },
  {
      "selector": ["classProperty"],
      "format": ["strictCamelCase"],
      "leadingUnderscore": "forbid",
      "trailingUnderscore": "forbid",
      "modifiers": ["protected", "readonly"]
  }
]
  • 正则^Enum[A-Z].*确保匹配以Enum开头且后续紧跟大写字母的属性,贴合枚举命名规范;
  • 把Enum规则放在前面,会优先匹配符合条件的属性,剩余protected readonly属性则应用strictCamelCase规则。

方案2:用@internal装饰器替代protected声明

如果不想调整ESLint规则,可通过@internal注释让枚举不显示在Storybook中,无需声明类属性:

import { EnumButtonSize } from './path-to-enum';

/** @internal */
EnumButtonSize;

模板中依然可以正常使用EnumButtonSize.LARGE,同时避免了类属性的命名规则冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:08:26