Skip to content

An introduction to ESLint

ESLint is a linter which helps to improve the code quality and fix bugs beforehand itself to avoid it from coming at runtime. It also helps to avoid hard to debug issues in future.

There are also other linters available like jslint, jshint but ESLint is the most widely used and popular.

ESLint displays warning or error message when-

  1. We use a variable without declaring it
  2. We re-declare the variable
  3. We try to change a constant value
  4. We add unnecessary parenthesis
  5. We use the wrong syntax

ESLint also provides suggestions based of preferred code style and wrong syntaxes.

TIP

Note that, ESLint just displays warning or error so you can fix it but it does not stop program from running. It just makes your coding better.

Installation

Setup ESLint ESLint Logo

Installing eslint

Create a new folder with name any and from inside that folder execute following command in terminal

console
$ npm init -y
console
$ yarn init -y

This will create a package.json file.

Now, Install the eslint package as dev dependency as it’s only used for development and not in production.

console
$ npm install eslint --save-dev
console
$ yarn add eslint --dev

Now, install the eslint in project by the command

Terminal
user@machine:~/project$ npm init @eslint/config@latest

It will ask some questions and create a file named eslint.config.mjs inside the eslint.config.mjs ,we can add our rules for checking code-

Click me to toggle the code
js
import globals from "globals";
import pluginJs from "@eslint/js";

/** @type {import('eslint').Linter.Config[]} */
export default [
  { languageOptions: { globals: { ...globals.browser, ...globals.node } } },
  pluginJs.configs.recommended,
  {

    rules: {

      "no-unused-vars": "warn", 
      semi: ["warn", "always"], 
    }, 
  }, 
];

For adding more rules ,visit the page Link

To run the eslint via terminal add the scripts in pakage.json file

json
 "scripts": { 
    "prepare": "husky",
    "lint":"eslint .", 
    "lint:fix":"eslint --fix"
  }, 

ESLint setup is now complete.To run the script execute the command npm run lint for showing the errors that was in the rules and npm run lint:fix for fixable errors.

Terminal
user@machine:~/project$ npm run lint
user@machine:~/project$ npm run lint:fix