ESLint with React gives `no-unused-vars` errors

前端 未结 6 724
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 05:00

I\'ve setup eslint & eslint-plugin-react.

When I run ESLint, the linter returns no-unused-vars errors for each React comp

相关标签:
6条回答
  • 2020-11-28 05:33

    To solve this only problem without adding new rules from react/recommended install eslint-plugin-react:

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

    add in .eslintrc.js:

    "plugins": ["react"]
    

    and:

    "rules": {   
         "react/jsx-uses-react": "error",   
         "react/jsx-uses-vars": "error" 
    }
    
    0 讨论(0)
  • 2020-11-28 05:34

    In your .eslintrc.json, under extends, include the following plugin:

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

    Source

    0 讨论(0)
  • 2020-11-28 05:35

    Quickest fix

    To ignore all TitleCase variables, add this to your ESLint config:

    {
        "rules": {
            "no-unused-vars": [
                "error",
                {
                    "varsIgnorePattern": "^[A-Z]"
                }
            ]
        ]
    }
    

    Correct fix

    Use eslint-plugin-react to ignore React variables.

    npm install eslint-plugin-react -D
    

    Add this to your ESLint config:

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

    Suggested fix

    Use eslint-plugin-react to improve your JSX usage, not just to silence this error.

    npm install eslint-plugin-react -D
    

    Add this to your ESLint config:

    {
        "extends": [
            "plugin:react/recommended"
        ]
    }
    

    If you use XO, refer to eslint-config-xo-react.

    0 讨论(0)
  • 2020-11-28 05:39

    Since I found this while googling, you should know that this simple rule is enough to prevent this message:

    react/jsx-uses-react
    

    The react/recommended set of rules adds many other rules you may not want.

    0 讨论(0)
  • 2020-11-28 05:41

    In my case I needed to add in your .eslintrc.js:

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

    plus a specific tweaking to rid of preact import: import { h } from 'preact' but you can use this example to get rid of your specific warnings like so:

        "no-unused-vars": [
            "error",
            {
                "varsIgnorePattern": "^h$"
            }
        ],
    
    0 讨论(0)
  • 2020-11-28 05:54

    If you create the project throught create-react-app CLI,You can npm run eject,and edit the package.json "eslintConfig" field,like this:

    `"eslintConfig": {
        "extends": "react-app",
        "rules": {
          "eqeqeq": "off",
          "no-unused-vars": "off",
        }
      },`
    

    the eslint will be closed

    0 讨论(0)
提交回复
热议问题