我希望对我的PascalCase项目中JSX.Element类型的变量强制使用React+Typescript。我经常使用以下模式来创建功能组件,并且我喜欢通过给它一个PascalCase名称来区分我的同名导出:
//MyComponent.tsx
//PascalCase for MyComponent
export const MyComponent= (): JSX.Element =>{
return (
<div>
My Component
</div>
)
}
export default MyComponent使用我当前的链接设置,我会得到一个警告,即Variable name `MyComponent` must match one of the following formats: camelCase, UPPER_CASE。如何将规则添加到链接器设置中,以便对类型为PascalCase的变量强制使用JSX.Element?
这是我现在的.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"
}
}
}发布于 2021-06-02 19:23:34
看起来这在声明的时候是不可能的(参见下面的链接)。但是,不正确的大小写不能超出声明文件的范围,因为小写名称是为内部类型(如div、span等)保留的。
// 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 />;在这里讨论没有特定于反应组件的规则:打字稿-埃斯林特/问题/2607
此外,不能保证返回JSX.Element的函数实际上是react组件。返回JSX.Element但不对组件作出反应的实用程序函数是一种相对常见的做法,这会导致误报。
发布于 2021-06-02 20:19:43
我认为eslint没有这种情况的设置,但是您可以创建自定义规则并应用它。请检查下面的链接是否相同。https://stackoverflow.com/a/49225308/13162789
https://stackoverflow.com/questions/67810998
复制相似问题