ESLint - rohit120582sharma/Documentation GitHub Wiki

In statically compiled languages, we usually lean on the compiler to catch out common errors. In dynamic languages we don’t have this luxury. JavaScript, being a dynamic and loosely-typed language, is especially prone to developer error. Without the benefit of a compilation process, JavaScript code is typically executed in order to find syntax or other errors.

Linting tools like eslint allow developers to discover problems with their JavaScript code without executing it. It is code quality tool that analyses your code and checks for common mistake that often leads to bugs.

There are three main reasons you should always install a linter:

  1. Enforce consistent code style - double quotes or single? Trailing comma or no? Most experienced engineers have a preference one way or another, but ultimately most agree that it doesn't really matter, so long as it's consistent. With eslint we can set up these preferences once, and the whole project will be checked to ensure the same style is followed.
  2. Catch mistakes - it's easy to miss typos, unused variables and forgetting to return a variable from a function while developing. When integrating eslint to your code editor, you'll get helpful warnings and errors for these issues while you're writing your code. Saves a lot of debugging time!
  3. Avoid bad practices - JavaScript is a pretty amazing language in that it allows you to do pretty much anything. This is very powerful, but dangerous, because it leaves it up to us, the developers, to have some rules and order. Depending on the code style you do with (e.g. functional vs object oriented) there are many linting rules that help you enforce good practices that go with the code style you prefer.

In many ways, it is similar to JSLint and JSHint with a few exceptions:

  • It uses Espree for JavaScript parsing.
  • It uses an AST (Abstract Syntax Tree) to evaluate patterns in code. It is a JavaScript object that describes your code.
  • It is completely pluggable, every single rule is a plugin and you can add more at runtime.


Installation

First, we should install the package. For this, open your terminal, navigate to the root directory of your project and run the following:

# For base
$ npm install --save-dev eslint eslint-config-prettier

# For ES6/7
$ npm install --save-dev babel-eslint

# For react
$ npm install --save-dev eslint-plugin-import
$ npm install --save-dev eslint-plugin-react
$ npm install --save-dev eslint-plugin-jsx-a11y

# For react-hooks
$ npm install --save-dev eslint-plugin-react-hooks


Configuration

It is intended for setting up and configuring ESLint on a per-project basis. You can setup a configuration file manually or by eslint cli and you’ll have a .eslintrc.json file in your directory.

$ ./node_modules/.bin/eslint --init

# Instead of navigating to `./node_modules/.bin/` you may also use `npx` to run eslint:
$ npx eslint --init

This particular configuration has a lot of rules to help you quickly catch common bugs like:

  • Take global variables from the environment of browser and node.
  • The import plugin helps ESLint catch commons bugs around imports, exports, and modules in general
  • jsx-a11y catches many bugs around accessibility that can accidentally arise using React, like not having an alt attribute on an img tag.
  • react is mostly common React things, like making sure you import React anywhere you use React.
  • Parse the code using babel-eslint before you're checking it. It is a parser that allows ESLint to use the same transpiling library, Babel, that Parcel uses under the hood. Without it, ESLint can't lint all valid ES6+ codes and understand JSX.
  • eslint-plugin-react requires you to inform of it what version of React you're using. We're telling it here to look at the package.json to figure it out.

Base configuration

{
    "extends": ["eslint:recommended", "prettier", "prettier/react"],
    "plugins": [],
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "env": {
        "es6": true,
        "node": true,
        "browser": true,
        "jest": true
    },
    "rules": {}
}

ES6/7 configuration

ESLint allows you to specify the JavaScript language options you want to support. By default, ESLint expects ECMAScript 5 syntax. You can override that setting to enable support for other ECMAScript versions as well as JSX by using parser options.

{
    "parser": "babel-eslint",
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module",
        "ecmaFeatures": {
            "experimentalObjectRestSpread": true
        }
    },
    "env": {
        "es6": true
    }
}

Configuration for React

{
    "extends": [
        "eslint:recommended",
        "plugin:import/errors",
        "plugin:react/recommended",
        "plugin:jsx-a11y/recommended",
        "prettier",
        "prettier/react"
    ],
    "plugins": ["react", "import", "jsx-a11y"],
    "parserOptions": {
        "ecmaVersion": 2018,
        "sourceType": "module",
        "ecmaFeatures": {
            "jsx": true
        }
    },
    "settings": {
        "react": {
            "version": "detect"
        }
    },
    "rules": {
        "react/prop-types": 1
    }
}

Configuration for React Hooks

{
    "plugins": ["react-hooks"],
    "rules": {
        "react-hooks/rules-of-hooks": 2,
        "react-hooks/exhaustive-deps": 1
    }
}

General rules configuration

{
    "rules": {
        "no-alert": "error",
        "no-console": ["error", { "allow": ["error", "warn"] }],
        "no-confusing-arrow": 0,
        "no-use-before-define": 0,
        "no-bitwise": ["error", { "allow": [">>>", "&", ">>", "<<"] }],
        "no-unused-expressions": ["error", { "allowTernary": true }],
        "no-trailing-spaces": ["error", { "skipBlankLines": true }],
        "indent": ["error", 4, { "SwitchCase": 1 }],
        "linebreak-style": ["error", "unix"],
        "quotes": ["error", "single", { "allowTemplateLiterals": true }],
        "semi": ["error", "always", { "omitLastInOneLineBlock": true }],
        "max-len": 0,
        "newline-per-chained-call": 0,
        "prefer-template": 2,
        "class-methods-use-this": 0,
        "arrow-parens": ["error", "always"],
        "arrow-body-style": [
            2,
            "as-needed",
            { "requireReturnForObjectLiteral": true }
        ],
        "comma-dangle": [1, "always-multiline"]
    }
}

ESLint - VSCode Integration

The ESLint plugin can be installed from the Visual Studio Marketplace, and gives easy integration with Visual Studio Code.

With the plugin set up, rather than having the ESLint as a task that needs to be invoked manually, it runs automatically, displays the results inline with your code, and updates as you type so you get the kind of user experience you’d expect from a spell-checker but with the complexity of your ESLint rules.



Run

To run eslint against our code we can use the following command:

$ npx eslint src/App.js

To make things a little easier to run, we can also add this command to the scripts section of the package.json file, making it look like this:

"script": {
	"lint": "eslint \"src/**/*.{js,jsx}\" --quiet"
}


Ingoring files

You can tell ESLint to ignore specific files and directories by creating an .eslintignore file in your project’s root directory. The .eslintignore file is a plain text file where each line is a glob pattern indicating which paths should be omitted from linting.

# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js
⚠️ **GitHub.com Fallback** ⚠️