Linting your React code with ESLint

Mattias Wikström
Go back

When first getting into the wonderful world of React earlier this year I used jsxhint to keep my code linted and free from the unnecessary errors that usually occur when I start hitting the keyboard at random. Starting up my new project for this course I was just about to install it again when I got the idea to actually look up if there had been any changes or something in the months since I last used it…

Well… DEPRECATED in big black letters is the first thing that meets me, which I guess in a terrifying way tells the story of being a web developer. Stay on your feet or be swallowed up by the shadows of out-dated frameworks and yesterdays junk. (Or embrace it an become a .NET-developer ;) )

ESLint to the rescue

A few minutes googling gave the overwhelming impression that ESLint is the new cool kid on the block. I happily expected to spend the rest of my day trying to grok it, a dream that was destroyed by this excellent blog post by Mr. Abramov (of Redux fame) himself that pretty much solved my problem perfectly. So please stop letting me waste your time and just click on over and read all about it.

TL;DR? OK, here’s a dumbed-down, no frills list on how to get going:

And you’re done! Just run npm run lint and… you might not see very much happening.

The thing with ESLint is that it’s an opt-in kind of linting - you have to add all the rules you want the linter to pick up on in your code - although if you created your .eslintrc using the --init helper eslint has automagically added the setting "extends": "eslint:recommended" that adds ESLints recommended rules. But please be free to peruse the official documentation on rules to specify the linting to your taste.

The react-plugin is not included in these recommended settings, so please head over to the plugin github page section on rules, they have pretty good docs explaining which rules do what. I just added all of them to begin with and removed the ones I didn’t like after a bit of experimenting, but if you use this approach, a word of caution: make it easier for yourself and change to another formatter - the default stylish one doesn’t show (at least it didn’t for me) which rule caused what warning/error. To use the compact formatter change your lint script to this:

// package.json
"scripts": {
    "lint": "eslint --format compact <FILE OR FOLDER TO LINT>"
    // probably some other scripts...

That should be it.

If you’ve gotten this far - congratulations! You should now have a functioning linter for all of your beautiful React code, have fun hacking away!