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

如何使用ESLint规则校验JSX属性值的kebab-case命名规范

解决JSX属性值的kebab-case格式校验问题

首先明确:@typescript-eslint/naming-convention规则仅负责校验标识符(变量名、属性名、函数名等)的命名,不处理JSX属性的字符串值校验,所以你用它达不到预期效果是正常的。

下面提供两种可行的解决方案:

方案一:利用内置no-restricted-syntax规则(ESLint v8.23.0+)

通过AST选择器定位目标属性的字符串值,配合自定义校验逻辑实现规则:

在你的ESLint配置文件(如.eslintrc.js)中添加以下规则:

module.exports = {
  // 其他配置项...
  rules: {
    "no-restricted-syntax": [
      "error",
      {
        // 定位名为attribute1的JSX属性的字符串字面量
        selector: "JSXAttribute[name.name='attribute1'] Literal",
        message: "attribute1的值必须为小写kebab-case格式",
        // 可选:自动修复不符合格式的值
        fix: (node) => {
          if (typeof node.value === 'string') {
            // 将字符串转为kebab-case(驼峰转短横线+全小写)
            const kebabValue = node.value.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
            node.value = kebabValue;
          }
        },
        // 校验逻辑:匹配小写kebab-case正则
        validate: (node) => {
          const kebabRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
          return typeof node.value === 'string' && kebabRegex.test(node.value);
        }
      }
    ]
  }
};

方案二:编写自定义ESLint规则(更灵活)

如果需要批量校验多个属性,或者需要更复杂的逻辑,推荐编写自定义规则:

  1. 创建自定义规则文件(如rules/jsx-attribute-kebab-case.js):
module.exports = {
  meta: {
    type: "problem",
    fixable: "code",
    schema: [
      {
        type: "object",
        properties: {
          attributes: {
            type: "array",
            items: { type: "string" },
            description: "需要校验的JSX属性名列表"
          }
        },
        required: ["attributes"]
      }
    ]
  },
  create(context) {
    const { attributes = [] } = context.options[0] || {};
    const kebabRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;

    return {
      JSXAttribute(node) {
        const attrName = node.name.name;
        if (!attributes.includes(attrName)) return;

        // 仅校验字符串类型的属性值
        if (node.value.type === "Literal" && typeof node.value.value === "string") {
          const value = node.value.value;
          if (!kebabRegex.test(value)) {
            context.report({
              node: node.value,
              message: `属性${attrName}的值必须为小写kebab-case格式`,
              fix(fixer) {
                const kebabValue = value.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, '$1-$2').toLowerCase();
                return fixer.replaceText(node.value, `"${kebabValue}"`);
              }
            });
          }
        }
      }
    };
  }
};
  1. 在ESLint配置中引入该规则:
module.exports = {
  // 其他配置项...
  plugins: ["custom-rules"], // 假设自定义规则放在项目根目录的custom-rules/plugins下
  rules: {
    "custom-rules/jsx-attribute-kebab-case": ["error", {
      attributes: ["attribute1"] // 指定需要校验的属性名
    }]
  },
  overrides: [
    {
      files: ["*.tsx", "*.jsx"],
      rules: {
        "custom-rules/jsx-attribute-kebab-case": ["error", { attributes: ["attribute1"] }]
      }
    }
  ]
};

注意事项

  • 若使用TypeScript,需确保ESLint配置中正确设置了parser: "@typescript-eslint/parser"和parserOptions: { ecmaFeatures: { jsx: true } },以支持TSX文件解析。
  • 自动修复逻辑仅针对驼峰转kebab-case的场景,若有其他特殊格式需求,可自行调整正则和转换逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 08:43:20