What is ESLint and How to Use ESLint to Detect and Fix Code for JavaScript Projects

What is ESLint and How to Use ESLint to Detect and Fix Code for JavaScript Projects

Problem

Developing a project is a long process that doesn't involve coding once but continues to use the code. In a project, the development time may be small compared to the testing and maintenance time.

With such a long duration, projects are likely to constantly change personnel. This means that there may be many people involved in writing code, each with their own coding style. We should not completely ban this, but with syntax rules such as line breaks, brackets, semicolons, etc., we can create a common set of rules and require everyone to adhere to them.

What is ESLint

ESLint is a static code analysis tool that quickly finds issues in your code. It is integrated into most text editors and you can run ESLint as part of your continuous integration/continuous deployment (CI/CD) process.

To do this, ESLint has a set of rules that you can configure to detect and prevent code violations. Furthermore, ESLint can also fix or format the code according to the integrated configuration.

ESLint provides extensions for different code editors, simply installing the ESLint extension will notify you of errors in real-time. To see a list of supported code editors, click ESLint Integrations.

Installation

You can install ESLint globally via npm.

$ npm i -g eslint

Then run init to initialize the ESLint configuration for your project. Note that you need to run init in the directory that contains the project you want to use ESLint with.

$ eslint --init

When running --init, ESLint will ask you a series of questions to create a suitable configuration, you simply need to answer according to what the project is using. Then a .eslintrc.js file will be created containing the configuration that ESLint will use for your project. (Note that if you choose a configuration in the form of a json or yaml file, ESLint will create the corresponding configuration file).

A default configuration when --init is run will look like this:

module.exports = {
    "env": {
        "browser": true,  
        "es2021": true
    },  
    "extends": "eslint:recommended",  
    "overrides": [
    ],  
    "parserOptions": {
        "ecmaVersion": "latest",  
        "sourceType": "module"
    },  
    "rules": {
    }
}

Basic Usage

The basic syntax to start running Lint is:

$ eslint [options] [file|dir|glob]*

For example, running Lint for the index.js file:

$ eslint index.js

ESLint will automatically find the .eslintrc configuration file in the project and Lint according to that configuration. You can also specify the configuration file for ESLint via the command line.

Suppose all your code is in the /src directory and you want to run Lint for the entire project:

$ eslint src

But I only want to run Lint for .js files and ignore files in the src/dist directory:

$ eslint src --ignore-pattern 'src/dist' --ext .js

There are many other useful CLI commands that you can refer to in the ESLint documentation page.

ESLint can also automatically fix code violations by running --fix:

# Fix violations but don't save changes
$ eslint src --fix-dry-run

# Fix violations and save changes
$ eslint src --fix

ESLint Rule

As I mentioned, ESLint has a set of rules that you can configure for your project. The list of rules can be found at ESLint rule.

To set a rule in the configuration is very simple, just add a property in the "rules" section with the value:

  • "off" or 0 - turn off the rule
  • "warn" or 1 - enable the rule in warning mode
  • "error" or 2 - enable the rule in error mode

For example, if I want to apply the no-extra-semi rule in error mode whenever Lint is run, I would do the following.

...  
    "rules": {
        "no-extra-semi": "error"
    }
...  

Recommended Rule Sets

ESLint offers many rules, and choosing which rules to apply can be a time-consuming and labor-intensive process, so there have been many rule sets created.

The most famous ones are the Airbnb and Google rule sets.

To use them is very simple, you just need to run npm install under the development package configuration (--save-dev), then declare the name of the configuration you want to use in the ESLint configuration file.

...  
    "extends": "google",  
    // or
    "extends": "airbnb",  
...  

Airbnb and Google provide clear descriptions of how to use their rule sets and the rules they apply in the Airbnb Style or Google Style documents.

Alternatively, you can also use the rule set recommended by ESLint themselves by setting "extends": "eslint:recommended".

Integration with Githook

Setting rules to create consistent style throughout the project, you need to prevent "push" code behavior that happens by mistake, intentionally, or forgetting to run Lint. By integrating with Githook, you can prevent such commits. If you don't know what Githook is, you can read more in the article What are Githooks? Learn how to use Githooks to prevent poor commits.

Summary

ESLint is an efficient tool for analyzing and modifying JavaScript code, helping to maintain consistent code style in your projects. Applying ESLint to a project is simple, and there are also integrated extensions for many Code Editors or IDEs to make your work easier.

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.
Author

Hello, my name is Hoai - a developer who tells stories through writing ✍️ and creating products 🚀. With many years of programming experience, I have contributed to various products that bring value to users at my workplace as well as to myself. My hobbies include reading, writing, and researching... I created this blog with the mission of delivering quality articles to the readers of 2coffee.dev.Follow me through these channels LinkedIn, Facebook, Instagram, Telegram.

Did you find this article helpful?
NoYes

Comments (1)

Leave a comment...
Avatar
Anh Đức1 year ago
Làm thế nào để thiết lập eslint với ci/cd được hả bạn
Reply
Avatar
Xuân Hoài Tống1 year ago
Bạn có thể tham khảo bài này https://2coffee.dev/bai-viet/su-dung-mien-phi-shared-runners-ci-cd-cua-gitlab và viết lệnh kiểm tra eslint vào mục script