DEV Community

Kazem
Kazem

Posted on • Edited on

How to Use ESLint to Boost Your Programming Skills

Image description

In this article I want to talk about a cool tool called code linter! It’s basically like a spell checker, but for code. Its main purpose is to catch any bad coding practices and help make sure that the code looks consistent and easy to read.

If you’re working on a project with other people, a code linter can be super helpful to make sure everyone’s code looks the same. This makes it easier for all of you to understand what each other’s code is doing and work together more efficiently. And if you’re working on a big project, having consistent code syntax is a real game-changer.

It makes it way easier for anyone to read and understand the code, no matter what part of the project they’re working on.

So, in short, a code linter helps minimize bad coding practices and makes sure the code looks consistent and easy to read. And that’s a great thing!

ESLint is one of the most popular linters in the JavaScript community. It can help you catch bugs and enforce coding standards, which will make your code more readable and maintainable.

I’m going to start off with a simple project using this command:

npm init -y
Enter fullscreen mode Exit fullscreen mode

Then add a simple JavaScript code like:

var example_varaible = "World"
let another_variable = "nothing"

function print(value) {
  const outputResults = 'hello ' + value + "!"
 console.log(outputResults);
}

print(example_varaible)
Enter fullscreen mode Exit fullscreen mode

If you run node script.js it works but there are a number of problems that might prevent code like this from your team!

  • Semicolons are inconsistent. Some lines have them, others don’t.
  • Quotations are inconsistent. Some code uses single, others double.
  • Some variable defined but never used
  • Some of variables defined in snake_case and other defined as camelCase

It is actually pretty easy to fix these issues on your own, but it becomes more challenging when you work as a team. That’s why integrating Eslint with your projects is a good idea. It reduces concerns about code quality and makes everything run more smoothly.

Installation

Now let’s add Eslint to our project with the following command:

npm install eslint --save-dev
Enter fullscreen mode Exit fullscreen mode

Now you need to initialize Eslint with creating a .eslintrc file in your root directory of project. You can have it by running the following command which will take you through a little questionnaire in your terminal about your requirement:

npx eslint --init
Enter fullscreen mode Exit fullscreen mode

Image description

And this is .eslintrc file

{
    "env": {
        "browser": true,
        "es2021": true
    },
    "extends": "eslint:recommended",
    "overrides": [
    ],
    "parserOptions": {
        "ecmaVersion": "latest"
    },
    "rules": {
    }
}
Enter fullscreen mode Exit fullscreen mode

The env section is like telling ESLint which environment your code will be running in. If you're writing code for the browser, you can set this to browser if its Nodejs use node.

extends is a cool feature that allows you to use a pre-made list of rules. ESLint comes with a list of recommended rules that you can use.

In parserOptions, you can specify which version of JavaScript your code is using. For example, if you set it to 2015, ESLint will give you an error if you use syntax like const or let instead of var. But if you set it to 2016, you can use const and let without any problems.

The rules section is where you can manually set rules for your project. You can choose whether you want ESLint to show a warning or throw an error if it finds a problem.

Now if you look the scripts.js file in your editor it shows problems clearly as bellow:

Image description

My VSC uses Error Lens extensions that highlight errors

You can also run following command to see all issue in script.js file:

npx eslint script.js
Enter fullscreen mode Exit fullscreen mode

Well, Let’s add some rules:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["eslint:recommended"],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "quotes": ["error", "double"],
    "semi": ["error", "always"],
    "no-console": "off",
    "indent": ["error", 2]
  }
}
Enter fullscreen mode Exit fullscreen mode

I added 4 rules to enforce double quotes, semicolons, removing no-console rule, and two levels of indentation. more rules are here.

Note that each rule can have one of these values:

  • "off" or 0 - turn the rule off
  • "warn" or 1 - turn the rule on as a warning (doesn’t affect exit code)
  • "error" or 2 - turn the rule on as an error (exit code will be 1)

Linting Your Project

With this configuration our script.js file has following issues:

Image description

It’s clear that this tool gave us the info we needed to fix our code. It not only tells us about the issues, but it also fixes some of the more basic syntax problems, like quotes and semicolons.

Run the command:

npx eslint script.js --fix
Enter fullscreen mode Exit fullscreen mode

Here is the results:

Image description

The problems with obvious solutions have been fixed, but sometimes it’s challenging especially when you extends your configuration with other rules.

Extending Configurations

Let’s take a look at another famous configuration you may need on your projects.

The first one is Airbnb which is based on the set of linting rules used by Airbnb software developers. To implement these guidelines for your code, you can easily install it by running the following command:

npm install eslint-config-airbnb --save-dev
Enter fullscreen mode Exit fullscreen mode

and add it into your .eslintrc file and inside extends section:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["eslint:recommended", "airbnb"],
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "quotes": ["error", "double"],
    "semi": ["error", "always"],
    "no-console": "off",
    "indent": ["error", 2]
  }
}
Enter fullscreen mode Exit fullscreen mode

Now if I do this with our example code the result could be like:

Image description

As you see, new rules and guides added and works perfectly and give us excellent tips.

Using ESLint with Prettier

By now, you’ve probably noticed that linters have two kinds of rules:

Formatting rules: max-len, no-mixed-spaces-and-tabs, keyword-spacing, comma-style, …

Code-quality rules: no-unused-vars, no-extra-bind, no-implicit-globals, prefer-promise-reject-errors, …

Previously in following article I talk about the power of Prettier and its formatting rules that reprint the entire program from scratch in a consistent way.



But if you want to use Eslint alongside Prettier most formatting rules of Eslint are unnecessary — even worse they might conflict with Prettier!

Here’s how to turn off rules that conflict with Prettier, or aren’t necessary:

1- Install following packages in your projects:

npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev
Enter fullscreen mode Exit fullscreen mode

2- Inside the .eslintrc add the following code:

"extends": ["eslint:recommended", "plugin:prettier/recommended"],
Enter fullscreen mode Exit fullscreen mode

3- Add your optional prettier configuration inside .prettierrc file:

{
  "printWidth": 80,
  "sem": true,
  "singleQuote": false,
  "tabWidth": 2
}
Enter fullscreen mode Exit fullscreen mode

In the following I add prettier to our sample code, as you can see the error is actually from prettier!

Image description

Using ESLint with React

If you are working with React, you can configure ESLint to work with JSX syntax. Here’s an example of a .eslintrc file for React:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
     "eslint:recommended",
     "plugin:react/recommended"
  ],
  "plugins": [
    "react"
  ]
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "quotes": ["error", "double"],
    "semi": ["error", "always"],
    "no-console": "off",
  }
}
Enter fullscreen mode Exit fullscreen mode

Using ESLint with Vue

And If you are working with Vue, you can configure ESLint to work with Vue templates. Here’s an example of a .eslintrc file for Vue:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
     "eslint:recommended",
     "plugin:vue/recommended"
  ],
  "plugins": [
    "vue"
  ]
  "overrides": [],
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "rules": {
    "quotes": ["error", "double"],
    "semi": ["error", "always"],
    "no-console": "off",
  }
}
Enter fullscreen mode Exit fullscreen mode

Using ESLint with Typescript

For Typescripts there are another lints like tslint (which is deprecated in 2021), also Eslint is a JavaScript linter and doesn’t support Typescripts internally but I strongly recommend that using it.

Sure, here is the steps that you need to configure Eslint with Typescripts:

In our project I add typescript configuration with following command:

tsc --init
Enter fullscreen mode Exit fullscreen mode

The command added tsconfig.json into root directory of the project (if you didn’t install typescript just add it by npm i -g typescript)

Now I can change script.js file into script.ts.

Next all the thing you need here is plugin and parser which enable Eslint to support Typescript language:

npm i typescript @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
Enter fullscreen mode Exit fullscreen mode

So you are ready to configure Eslint like this:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": [
    "eslint:recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended"
  ],
  "overrides": [],
  "parser": "@typescript-eslint/parser",
  "parserOptions": {
    "ecmaVersion": "latest",
    "sourceType": "module"
  },
  "plugins": ["@typescript-eslint"],
  "rules": {
    "no-console": "off",
    "camelcase": "warn"
  }
}
Enter fullscreen mode Exit fullscreen mode

I also added prettier in configurations and here is the result:

Image description

Spectacular!! we’ve configured Eslint with Typescript and prettier.

Conclusion

ESLint is a powerful tool that can help you catch bugs and enforce coding standards in your JavaScript, React, Vue, and TypeScript projects. By using ESLint, you can improve the quality and maintainability of your code. If you are new to programming, it may take some time to get used to using ESLint, but the effort is well worth it in the long run.

I am attaching the tutorial code here for your reference.

Happy coding!!!

Top comments (0)