【发布时间】:2021-03-30 19:43:00
【问题描述】:
我正在将 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 来抛出错误 - TypeScript 本身将无法编译。 Intellisense 还会在 IDE 中显示问题。
-
我的 IDE 运行正常并突出显示错误。然而,TypeScript 编译时没有错误,无论是在开发中还是在我构建生产时。仅我的 IDE 是不够的,因为它仅在我当前正在查看文件时才显示错误。我已经编辑了问题并附上了我的 tsconfig.json
标签: reactjs typescript eslint eslintrc typescript-eslint