Should not have to disable eslint when using with react

Viewed 962

So consider the following eslint file:

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

It's pretty basic. I use the eslint:recomended extension and the react plugin.

Now consider the following file:

import React from 'react'; // eslint-disable-line
import ReactDOM, { render } from 'react-dom'; // eslint-disable-line
import StartUp from './components/startup.js'; // eslint-disable-line

render(
  <StartUp />,
  document.getElementById('app')
);

Notice the disables. If I turned off elsint this whole system works fine, nothing fails to import, everything is found, the whole app loads fine.

But if I remove those disables I get the following:

  1:8  error  'React' is defined but never used     no-unused-vars
  2:8  error  'ReactDOM' is defined but never used  no-unused-vars
  3:8  error  'StartUp' is defined but never used   no-unused-vars

This should not be happening. What do I have to configure for it to understand that these are not "never used"?

3 Answers

Since you're using Webpack, you can circumvent ESLint entirely and just make sure that React and ReactDOM are available anywhere using the ProvidePlugin. You can use it just like this in your Webpack config file:

const webpack = require('webpack');

module.exports = {
  // The rest of your config file...
  ...,
  plugins: [
    new webpack.ProvidePlugin({
      React: 'react',
      ReactDOM: 'react-dom'
    })
  ]
};

For the last one, make sure you've installed the ESLint React plugin

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

Then include the plugin and make sure you enable the jsx-uses-vars rule.

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

Then your code could be written like this:

import { render } from 'react-dom';
import StartUp from './components/startup.js';

render(
  <StartUp />,
  document.getElementById('app')
);

I think you can add React and these others as a global in your .eslintrc files.

Related