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

如何配置ESLint选择器以选中包含特定类名的JSX元素?

如何配置ESLint选择器以选中包含特定类名的JSX元素?

嘿,我来帮你搞定这个ESLint选择器的问题~你之前的选择器没生效,主要是没摸准JSX的AST结构,咱们一步步调整:

先搞懂问题出在哪

你之前用的选择器比如JSXElement JSXAttribute JSXIdentifier[name="className"] + Literal[value="bg-red"],这里的+是兄弟选择器,但在JSX的AST结构里,className属性的名称(JSXIdentifier)和属性值(Literal)并不是兄弟节点——它们都属于同一个JSXAttribute节点的子内容,所以用兄弟选择器根本匹配不到。

另外你尝试的JSXAttribute[name="className"][value="bg-red"]也不对,因为JSXAttribute本身没有value属性,它的属性值是作为子节点存在的Literal对象。

正确的选择器写法

1. 精确匹配某个类名(比如"bg-red")

如果要精准检测className="bg-red"的情况,用这个选择器:

'no-restricted-syntax': [
  'error',
  {
    selector: 'JSXElement JSXOpeningElement JSXAttribute[name.name="className"] Literal[value="bg-red"]',
    message: 'Do not set background colors directly.',
  },
],

关键点说明:

  • JSXAttribute[name.name="className"]:JSXAttribute的name属性是一个JSXIdentifier对象,它的name字段才是字符串"className",所以要用name.name来匹配
  • 用后代选择器连接Literal,因为它是JSXAttribute的子节点,对应属性值

2. 匹配以bg-开头的类名(更灵活的场景)

如果要检测所有包含以bg-开头的类(比如bg-red、bg-blue甚至text-white bg-green这种多类情况),可以用正则匹配Literal的value:

'no-restricted-syntax': [
  'error',
  {
    selector: 'JSXElement JSXOpeningElement JSXAttribute[name.name="className"] Literal[value=/\\bbg-/]',
    message: 'Do not set background colors directly using bg- classes.',
  },
],

解释一下:

  • value=/\\bbg-/:用正则匹配包含bg-且前面是单词边界的字符串,这样不会误判xbg-red这类不符合预期的类名;注意在字符串里要把反斜杠转义成\\
  • 这个选择器会匹配所有className里包含任意bg-开头类的JSX元素

测试验证

把上面的选择器替换到你的ESLint配置里,再测试你写的TestComponent,就能正确触发错误提示啦~

备注:内容来源于stack exchange,提问作者Get Off My Lawn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 13:13:02