You need to enable JavaScript to run this app. 如何在ESLint中配置规则强制JSX.Element类型变量使用PascalCase命名
优惠活动
大模型
产品
解决方案
定价
更多

如何在ESLint中配置规则强制JSX.Element类型变量使用PascalCase命名

解决方案

你当前遇到的警告是@typescript-eslint/naming-convention默认规则只允许变量使用camelCase和全大写下划线命名,没有为返回JSX的组件函数做特殊适配,你只需要替换原配置里的@typescript-eslint/naming-convention规则即可。

修改步骤

  • 把.eslintrc.json中rules字段下的"@typescript-eslint/naming-convention": "warn"替换为以下自定义配置:
"@typescript-eslint/naming-convention": [
  "warn",
  // 普通变量默认规则
  {
    "selector": "variable",
    "format": ["camelCase", "UPPER_CASE", "PascalCase"],
    "leadingUnderscore": "allow"
  },
  // 针对返回JSX.Element的函数变量,强制要求PascalCase
  {
    "selector": "variable",
    "types": ["function"],
    "filter": {
      "type": "return",
      "data": "JSX.Element"
    },
    "format": ["PascalCase"],
    "leadingUnderscore": "allow"
  },
  // 其他基础命名规则,和官方推荐保持一致
  {
    "selector": "function",
    "format": ["camelCase", "PascalCase"]
  },
  {
    "selector": "typeLike",
    "format": ["PascalCase"]
  }
]
  • 重启ESLint服务即可生效,之后所有显式声明返回JSX.Element的函数变量都会被要求使用PascalCase命名,普通变量仍保持原有命名规则校验。

完整配置参考

修改后的完整.eslintrc.json如下:

{
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": 2018,
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint", "react-hooks"],
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended"
  ],
  "rules": {
    "react-hooks/rules-of-hooks": "error",
    "react-hooks/exhaustive-deps": "warn",
    "react/prop-types": "off",
    "@typescript-eslint/naming-convention": [
      "warn",
      {
        "selector": "variable",
        "format": ["camelCase", "UPPER_CASE", "PascalCase"],
        "leadingUnderscore": "allow"
      },
      {
        "selector": "variable",
        "types": ["function"],
        "filter": {
          "type": "return",
          "data": "JSX.Element"
        },
        "format": ["PascalCase"],
        "leadingUnderscore": "allow"
      },
      {
        "selector": "function",
        "format": ["camelCase", "PascalCase"]
      },
      {
        "selector": "typeLike",
        "format": ["PascalCase"]
      }
    ],
    "@typescript-eslint/explicit-function-return-type": [
      "warn",
      {
        "allowExpressions": true
      }
    ]
  },
  "settings": {
    "react": {
      "pragma": "React",
      "version": "detect"
    }
  }
}

如果你项目中使用React.FC/React.FunctionComponent类型声明组件,可以在filter中补充对应类型匹配规则,即可覆盖所有组件声明场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 17:15:05