Set Up Airbnb’s Linter (React + Node)

Written by jballin | Published 2018/08/11
Tech Story Tags: javascript | eslint | programming | web-development | react

TLDRvia the TL;DR App

let’s get your code squeaky clean

A linter flags anything in your code that breaks its pre-defined rules (“style guide”). Each style guide has different opinions about what constitutes “good” JavaScript code. This post uses Airbnb’s style guide; Google’s is also popular.

Although some developers install their linter globally, this post aims to be more precise by creating a custom configuration for each project.

First, let’s set up ESLint (one of the most popular linter tools). Luckily, ESLint has a magical tool built right in! 🎩

$ cd PROJECT$ npx eslint --init

This will ask a series of questions about your desired set up. My choices:

"To check syntax, find problems, and enforce code style"(if React, "JavaScript, if Node "CommonJS"(if React, "React")(if React, "Browser", if Node "Node")Use a popular style guideAirbnbJavaScriptYes

I’m using yarn, why did it create a package-lock.json file!? 😡

$ rm package-lock.json$ yarn install

Skip to ⚛️ if you used Create React App

How do I run this thing? 🤔

Add eslint . && to the beginning of your test script (i.e. eslint . && mocha) in your package.json. This will run eslint (on the command line) every time you run npm test. Alternatively, just make a lint script which runs eslint . if you want to keep it separate from test. You should run both scripts in the root directory so it lints your entire project.

My test files have so many errors! 😕

Just add mocha (or another test framework) to your .eslintrc.js:

{"env": {"mocha": true}}

⚛️ Create React App

CRA comes with ESLint built in, but it’s intentionally forgiving (doesn’t warn about console.log, semicolons, etc.). But we ain’t scared of nothing, let’s lint the “crapp” out of our projects. 💪

So many errors in my React App!? 😰

1. Tell eslint to ignore serviceWorker.js

$ echo src/serviceWorker.js > .eslintignore

2. Add jest and babel-eslint to your .eslintrc.js:

{parser: 'babel-eslint',env: {jest: true,}}

3. Change all jsx files to have a .jsx file extension

4. Add a lint script to your package.json which tells eslint to look at .jsx files in addition to .js files:

"lint": "eslint --ext .js --ext .jsx ."

Now you can run eslint's auto-fix:

$ yarn lint --fix

Use $ yarn lint or $ npm run lint from the command line (in the root directory) to lint your app. CRA’s built-in linter will still function the same and show up in the console and in terminal when starting the app.

RELATED: instructions for setting up ESLint in Atom, so you can see the warnings directly in your text editor

Did this work? Did you get stuck? Let me know! ✌️


Written by jballin | sup world
Published by HackerNoon on 2018/08/11