ESLint
June 22, 2016
Linting is cool. It keeps people from making stupid mistakes and can make your code a lot neater/easier to read.
Not linting is how you end up with spaghetti code that no one can read.
Lint everything. HTML, CSS, JS, Python, Ruby, PHP, etc.
ESLint lints JS really nicely.
There was JSHint and JSLint, but they were hard to extend so someone made a JS linter that was easy to extend called ESLint. It’s now the standard.
Agree with your team on a coding style. This part isn’t super important and there are a ton of well thought out configs out there already like AirBnB. What’s important is you all agree to do the same code style!
How to use ESLint
Use npm. It’s easy and portable.
cd ~/playgrounds/eslint
echo '{}' > package.json
npm install --save-dev eslint-config-airbnb eslint-plugin-import eslint-plugin-react eslint-plugin-jsx-a11y eslint
(AirBnB usage)
Note: I feel ya. All of these npm packages seem silly, but it’s the whole Unix philosophy of making everything modular. It’s a bit annoying, but overall it’s usually a good thing.
- At this point you could do something like
eslint --init
to make an ESLint config file. In that file, you could add something like"extends": "airbnb"
, but that’s newb stuff. Do we really need yet another config file? - Do this instead: in your
package.json
add an"eslintConfig"
object with"extends": "airbnb"
in it.
Protip: If you’re configuring some npm package, see if you can put it in
package.json
instead of having 20 config files polluting the root of your project.
- Now you could run
node_modules/.bin/eslint
in terminal (and this is actually cool/useful for the--fix
flag), but you don’t want to be switching between terminal and editor after every keystroke to see if you made a mistake, so install an editor plugin for ESLint. Here’s Atom’s. ESLint is insanely popular so there is almost certainly a plugin for your editor. - Restart your editor and type some sloppy, error-filled, JS. Your editor should light up like a Christmas tree.
What if I have some global variables? jQuery doesn’t work! alert()
is throwing an error!
Config it!
"eslintConfig": {
"extends": "airbnb",
"env": {
"jquery": true
},
"rules": {
"no-alert": "off"
}
}
Congrats
Now you’re linting your JS like a pro. Enjoy your impending OCD.
Homework
- Experiment with some other configs (standard is currently my favorite).
- Write your own config.
- Skim through the rules and read what some of them do.
- Skim through some configuration options so when something breaks you might have an idea as to what’s wrong.