Using eslint with react

When developing a big project in React, it is important to maintain some standard code practises. This is where lint comes in. I will be using the common standardjs.com rules in the article.

NPM

In your project install the following commands using npm:

npm install --save-dev eslint eslint-{config-standard,plugin-standard,plugin-promise,plugin-import,plugin-node,plugin-react}
npm install --save-dev babel-eslint@next

.eslintrc

In your project root add a file called ‘.eslintrc’ and add the following json:

{
  parser: "babel-eslint",
  env: {
    es6: true,
    "browser": true
  },
  parserOptions: {
    ecmaversion: 6,
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true
    }
  },
  extends: ["eslint:recommended","plugin:react/recommended","standard"],
  plugins: [
    "react"

  ]
}

Parser will be used to specify that we need to parse lint using babel, for which we installed the babel-eslint@next in npm.

Env and parserOptions are optional and will simply specify the env options that lint may encounter during parsing.

Extends is the most important since it will specify what kind of rules will be set. You can use only “standard” if you would like however both eslint and react lint plugin come with inbuilt recommendations that I decided to use above too.

Plugins above is simply there to tell lint that react is used to avoid getting react errors such as unused imports etc.

package.json

In our package.json, add 2 scripts that will help you use lint quicker:

"scripts": {
  "lint": "eslint app/.",
  "fix": "eslint --fix app/.; exit 0;"
}

“lint” script will check for errors while “fix” script will TRY to auto fix as many errors/warnings as possible such as end of file line, extra spacings, etc.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s