ESLint with React 给出了 “no-unused-vars” 错误

2022-08-30 04:45:19

我已经设置和.eslinteslint-plugin-react

当我运行 ESLint 时,linter 会为每个 React 组件返回错误。no-unused-vars

我假设它没有认识到我正在使用JSX或React语法。有什么想法吗?

例:

应用程序.js

import React, { Component } from 'react';
import Header from './header.js';

export default class App extends Component {
  render() {
    return (
      <div>
        <Header />
        {this.props.children}
      </div>
    );
  }
}

林特错误:

/my_project/src/components/app.js
  1:8  error  'React' is defined but never used   no-unused-vars
  2:8  error  'Header' is defined but never used  no-unused-vars

这是我的.eslintrc.json文件:

{
    "env": {
        "browser": true,
        "es6": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true,
            "jsx": true
        },
        "sourceType": "module"
    },
    "plugins": [
        "react"
    ],
    "rules": {
        "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
        "indent": [
            "error",
            2
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "single"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
}

答案 1

首先,安装以下模块 。npm install --save-dev eslint-plugin-react

然后,在 下 ,包括以下插件:.eslintrc.jsonextends

'extends': [
    'plugin:react/recommended'
]


答案 2

要解决这个唯一的问题,而无需从安装中添加新规则:react/recommendedeslint-plugin-react

npm install eslint-plugin-react --save-dev

加入:.eslintrc.js

"plugins": ["react"]

和:

"rules": {   
     "react/jsx-uses-react": "error",   
     "react/jsx-uses-vars": "error" 
}