首页 > 解决方案 > 在 eslint 规则中为 JSX.Element 类型的变量指定 PascalCase 命名约定

问题描述

我想对JSX.Element我的 React+Typescript 项目中的类型变量强制执行 PascalCase。我经常使用以下模式来创建功能组件,并且我喜欢通过给它一个 PascalCase 名称来区分我的同名导出:

//MyComponent.tsx
//PascalCase for MyComponent 
export const MyComponent= (): JSX.Element =>{  
  return (
    <div>
      My Component
    </div>
  )
}
export default MyComponent

使用我当前的 linter 设置,我收到一个警告,即Variable name `MyComponent` must match one of the following formats: camelCase, UPPER_CASE. 如何在我的 linter 设置中添加一条规则,对 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",
    "@typescript-eslint/explicit-function-return-type": [
      "warn",
      {
        "allowExpressions": true
      }
    ]
  },
  "settings": {
    "react": {
      "pragma": "React",
      "version": "detect"
    }
  }
}

标签: typescripteslint

解决方案


看起来目前在声明时是不可能的(见下面的链接)。但是,不正确的大小写不能扩散到声明它的文件之外,因为小写名称是为诸如 , 等内在类型保留divspan

// my-component.tsx
export const myComponent: FC<{}> = () => (
  <div>My Component</div>
);

export default myComponent;
// app.tsx
import { myComponent } from './my-component';

// Fails to compile with: Property 'myComponent' does not
// exist on type 'JSX.IntrinsicElements'.  TS2339
const App = (): JSX.Element => <myComponent />;

在默认导出的情况下,声明文件中使用的名称被有效地删除,因为它只是分配给在导入文件中选择的任何名称:

// app.tsx
import SomeOtherName from './my-component';

const App = (): JSX.Element => <SomeOtherName />;

在此处讨论没有特定于 React 组件的规则:typescript-eslint/issues/2607

此外 - 不能保证返回 JSX.Element 的函数实际上是一个反应组件。返回 JSX.Element 但不是反应组件的实用函数是一种相对常见的做法,这会导致误报。

编辑:以下不正确。

这不是组件的正确类型。你的组件函数应该是 `React.FunctionalComponent` 类型(或其更短的别名 `FC`)。这样的组件**返回**一个`ReactElement`。
import { FC } from 'react';

const MyComponent: FC<{}> = () => {
  return (
    <div>
      My Component
    </div>
  )
}

推荐阅读