问题描述
我正在将 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 识别出丢失的 prop 并将突出显示它,但是我仍然可以成功编译代码,这是不应该的。
如何修改我的 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"
}
};
{
"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 版修复了该问题。