Los Angeles, CA

How to setup ESLint to use AirBnB’s React rules with a React application

How to setup ESLint to use AirBnB’s React rules with a React application

Setting up ESLint can seem daunting but luckily we can help

 We hope you know why you are doing it but if not in short ESLint and Prettier can help your team maintain code quality and same formatting throughout the project.

If your company has more than 1 frontend developer you will realize different developers use different editors and they want to stick to it. Most of the developers are used to the inline formatting functionality that comes with the IDE but unfortunately the most popular ones like Atom, Visual Studio Code and Webstorm each format the code differently.

What prettier does is gets everyone on the same page. Just add a .prettierrc file to your project, have all devs download the prettier plugin for their fave editor. Doing so will provide your team and especially the code reviewers some sanity.

Prettier

Step 1. Make sure you are in the project root directory and then use Yarn or NPM to add three prettier related packages.

yarn add -D prettier eslint-config-prettier eslint-plugin-prettier

ESLint

Step 2. Make sure you are in the project root directory and then use Yarn or NPM to add these ESLint packages

yarn add -D eslint eslint-plugin-react eslint-config-airbnb eslint-plugin-jsx-a11y eslint-plugin-import

 

Step 3. In the project root directory create a file with the following name :
.eslintrc or .eslintrc.js or .eslintrc.json

Don’t create 3 files 🙂

We’ll add a .eslintrc.json

{
  "extends": ["airbnb", "prettier", "prettier/react"],
  "plugins": ["react", "prettier"],
  "rules": {
    "react/jsx-filename-extension": [
      1,
      {
        "extensions": [".js", "jsx"]
      }
    ],
    "prettier/prettier": "error",
    "max-len": ["error", 80]
  },
  "env": {
    "browser": true
  }
  
}

What we’ve done in the example above is used the recommended config from airbnb and prettier

so a good question is: Does the order matter?

The short answer is YES 

To get started we’ve also added a few rules illustrate that we are extending our rule set while using the base rules from Airbnb and prettier

The “react/jsx-filename-extension” rules that we have added will allow us to write JSX in files with .js extension

Feel free to modify these rules to fit your style.

 

Next question: ok how do I now invoke the linter to go through all my files?

Step 4. To invoke your linter go to package.json and in the scripts section add the following

"lint": "eslint src -c .eslintrc.json --ext js,jsx"

Save your package.json and try running

yarn lint

or

npm run lint

This will lint the files that have the extension .js or .jsx in the src directory while respecting your rules in .eslintrc.json config file.

You can also modify this lint command to suit your needs.

Did we miss anything? Did it work for you?

Facebook Comments