如何在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
相关产品推荐
相关产品推荐

