[英]How do you check for prop errors in a React/Typescript project with ESLint?
我正在将 create-react-app Typescript 项目迁移到最新版本的 create-react-app,并且我正在从现在已弃用的 tslint 迁移到 eslint。 我在此过渡中遇到的问题是,我无法让 eslint 对缺少的道具抛出错误或警告。
以这个示例 React 组件为例:
interface Props {
name: string;
count: number;
}
const ExampleComponent = (props: Props) => {
const {name, count} = props;
return (
<div>
{name} {count}
</div>
);
}
export default ExampleComponent;
然后由另一个组件调用:
import ExampleComponent from './ExampleComponent';
const App = (props: Props) => {
return (
<ExampleComponent count={5} />
);
}
在上面的示例中,缺少count
属性。 这应该会导致 eslint 抛出错误或警告,就像之前对 tslint 所做的那样。 我的 IDE 识别出缺少的道具并突出显示它,但是我仍然可以成功编译代码,这是不应该的。
如何修改我的 eslint 配置,以便在缺少道具时出现错误(或者在同样的意义上,如果存在不应该存在的额外道具)?
这是我的.eslintrc.js
:
module.exports = {
"env": {
"browser": true,
"node": true
},
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "tsconfig.json",
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": [
"eslint-plugin-jsdoc",
"eslint-plugin-prefer-arrow",
"eslint-plugin-import",
"eslint-plugin-react",
"@typescript-eslint",
"@typescript-eslint/tslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended",
],
"rules": {
"@typescript-eslint/no-inferrable-types": "off",
"react/no-unescaped-entities": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"jsdoc/require-jsdoc": "off",
"@typescript-eslint/no-unused-vars": "off",
"max-len": ["error", 200, 2, {
"ignoreUrls": true,
"ignoreComments": true,
"ignoreRegExpLiterals": true,
"ignoreStrings": true,
"ignoreTemplateLiterals": true
}],
"no-prototype-builtins": "off"
}
};
下面是我的tsconfig.json
文件:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"strictFunctionTypes": false,
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"allowJs": true,
"skipLibCheck": true,
"noEmitHelpers": false,
"noUnusedLocals": true,
"removeComments": false,
"preserveConstEnums": false,
"sourceMap": true,
"importHelpers": true,
"noFallthroughCasesInSwitch": true,
"noUnusedParameters": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react"
},
"include": [
"src"
],
"exclude": [
"build",
"node_modules",
"src/setupProxy.js",
"archived"
]
}
问题不是 ESLint 没有捕获错误的问题,而是在迁移到最新版本的 create-react-app 的过程中。 更新react-scripts
(在撰写本文时为 4.0.1 版本)不会同时更新 TypeScript 版本。 不同的版本会导致一些错误没有被正确报告。 将 Typescript 更新到版本 4.0.3 可解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.