A brief tutorial on ESLint

Sat Feb 25 2017

Paul Shan

As we all know JavaScript is an interpreted language and you won’t come to know about the errors till the time you run the program and it hits the error prone code. This behavior leads wastage of time and hampers productivity.
A solution of the above mentioned problem are linting tools like JSLint, JSHint and ESLint. These tools helps you to find bugs, unused or bad code areas, bad coding practices and alignment issues.
Though all of these three has the same goal; but ESLint is slightly ahead of the other two. Probably you will understand the difference if you read the history behind ESLint creation.

History behind the birth of ESLint

  • Years ago, JSLint was the master in JavaScript linting.
  • Then JSHint came into the picture who forked JSLint to increase the flexibility.
  • JSHint was pretty popular and even the creator of ESLint, Nicholas C. Zakas was using it heavily in his lion-share projects.
  • At some point Nicholas started to feel stifled and frustrated as well as there was no easy way to add additional rules to JSHint.
  • That frustration gradually become big and the result was ESLint.

Advantages of ESLint

  • Easy to create and incorporate new rules.
  • Dynamic rule loading is possible.
  • No confusing configuration; all rules are turned on and off the same way.
  • A particular rule can be configured as error or warning.
  • ESLint return a non-zero error code in case of error but zero for warnings. This helps taking decisions on next unix code running.
  • You can see which rule is causing which error in the output.

Basic installation & kickoff

ESLint is available as a npm package. Hope you are already familiar with node js and npm; and can easily install the package eslint in your machine globally.

//run in terminal

npm install -g eslint

After the global installation is done, you need to configure the rules before you do anything else with your ESLint. Run the command below in your project’s root folder to configure.

//run in terminal

eslint --init

After you run the init command, it will show you a question “How would you like to configure ESLint?” with three probable options. You can use the up & down arrow key of your keyboard to navigate the options and hit enter to select.

eslint-init-questions-0

You can select the first option, “Answer question about your style” as you’re just starting with ESLint. After selecting the option it will ask you more questions. You can refer the screenshot below to address them.

eslint-init-questions-1

I haven’t included common js, JSX etc cause I’m going to show you a simple native JavaScript application. But in case you need them, you can install. Anyway, after answering all the questions, it will create a file .eslintrc.json in your project’s base folder. The created file will look like the following.

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "sourceType": "module"
    },
    "rules": {
        "indent": [
            "error",
            4
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
} 

Now that your basic ESLint setup is done, you can run it to check the linting errors in your project. All you need to do is, running the following command in your project’s root directory.

//run in terminsl

eslint .

Or you can provide the path of any folder or file in your project as a parameter, instead of . and eslint will throw errors only for that file/folder. I have only one file in my project which is like the following.

function sum(x,y) {
    return x + z;
}

sum(20,30)

If I run eslint . now, it will show me the errors as the following screenshot.

eslint-init-questions-2

Auto fix errors

Though most of the errors can be resolved by manual effort; but ESLint also provides a flag called --fix to help you auto fixing the errors wherever possible. Below is the command.


eslint --fix .

Customizing basic rules

Now that you know how to install ESLint in your project and setup & run the basic things; let’s talk about how can we manipulate the rules.
Hope you remember that initializing ESLint in our project, automatically created a .eslintrc file. Let’s discuss a bit more about the file.

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "sourceType": "module"
    },
    "rules": {
        "indent": [
            "error",
            4
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "error",
            "always"
        ]
    }
} 

The first property of this JSON is env or environment. You can change the boolean properties inside that. The property extends means the basic rules have been extended or inherited from eslint:recommended. And the rules property contains the set of rules to be override the eslint:recommended ones. The rules are kind of self explanatory, so I’m not writing what are their functionalities, but I’m changing the rules like below and will see what happens if I run the eslint . again.

{
    "env": {
        "browser": true,
        "es6": true,
        "node": true
    },
    "extends": "eslint:recommended",
    "parserOptions": {
        "sourceType": "module"
    },
    "rules": {
        "indent": [
            "error",
            2
        ],
        "linebreak-style": [
            "error",
            "unix"
        ],
        "quotes": [
            "error",
            "double"
        ],
        "semi": [
            "warn",
            "always"
        ]
    }
}
eslint-init-questions-3

So, changing the .eslintrc.json we have been able to convert the errors to warnings and also have change some indentation rules. So this is how we can play with the .eslintrc.json to customize the rules according to our need. You can go through ESLint official rules page to find out more rules to add in your project.

eslint command

Till now we were using the command eslint, cause it was installed globally. However it’s not the best practice, cause we can’t force everyone in the team to install something globally. So better install the eslint locally in the project. You should run the npm install command like below.

//run in project's base folder

npm install eslint --save-dev

We should also change the test command in our package.json file to make eslint run with npm test command. Below is the snippet of package.json.

{
  "name": "my-test-proj",
  "version": "1.0.0",
  "description": "To test eslint",
  "main": "index.js",
  "scripts": {
    "test": "eslint ."
  },
  "author": "Paul Shan",
  "license": "MIT",
  "devDependencies": {
    "eslint": "^3.16.1"
  }
}

Now you or anyone else in the team should be able to run npm test command and find the linting errors.

Integration with git hook

Manually running npm test every-time may not be a feasible solution cause the developers will often forget to do so. So the better idea is to add an automation. The best place for auto testing will be the git pre-commit hook, cause we have to restrict the developer if any the code contains any linting errors.
The easy way to do so in the project level is by introducing the pre-commit package. We can install this npm package and save it as a dev dependency (npm i pre-commit --save-dev).
After installing modify the package.json file to include a new property pre-commit which will have an array of commands as value. You need to add test command over there.

{
  "name": "my-test-proj",
  "version": "1.0.0",
  "description": "To test eslint",
  "main": "index.js",
  "scripts": {
    "test": "eslint ."
  },
  "author": "Paul Shan",
  "license": "MIT",
  "devDependencies": {
    "eslint": "^3.16.1",
    "pre-commit": "^1.2.2"
  },
  "pre-commit": [
    "test"
  ]
}

Now if you try to commit any file which has linting errors; it will be rejected.

Linting errors in editor

Modern days editors like Sublime text, Atom, WebStorm etc are very smart and flexible. You can install different plugins in those editors to enhance their features. To get ESLint errors and warnings in your editor itself, you can install ESLint plugin of that editor. You can google “ESLint plugin in YourEditorName” to get suggestions and you can choose anything of your choice.

SHARE THIS ARTICLE

post-thumbnail
Today everyone knows the importance of a lightning-fast website and how the speed impacts the conversion rate of a business. Today, everyone wants the site to be a PWA so that the mobile users can have an app-like experience with the website because, for the majority of the merchants, the customers come through mobile devices.
Tue Apr 20 2021
post-thumbnail
Here we are going to see how you can manage backup and restore of Postgres database with docker.
Thu Sep 03 2020
post-thumbnail
Image sliders or carousels always have increased the UI attraction of websites and they are pretty useful for reflecting the major roles/products too. In case, I am having a website that sells tee-shirts,
Mon Apr 30 2018

About VoidCanvas

This blog was created out of hobby and talks mostly about technology, web development, JavaScript, NodeJS and related topics. Thank you for reading my blog.

Copyright 2022 - www.voidcanvas.com

Popular Articles

Authentication using Google's oAuth api with node.js

Thu Mar 10 2016

OAuth authentications are pretty popular now a days and another thing which is popular is JavaScript. This article shows how to plugin google’s oAuth api for authentication in your own node application.

CSS3 Loader Snippet Collection: (Part 2 - Squares)

Sat Mar 01 2014

This is a continuation of my CSS3 loader snippet collection series. I've provided spinning css3 animation loader in the part 1 of this series and here in part 2, I'm providing various square type loading