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

Daily short news for you
  • Privacy Guides is a non-profit project aimed at providing users with insights into privacy rights, while also recommending best practices or tools to help reclaim privacy in the world of the Internet.

    There are many great articles here, and I will take the example of three concepts that are often confused or misrepresented: Privacy, Security, and Anonymity. While many people who oppose privacy argue that a person does not need privacy if they have 'nothing to hide.' 'This is a dangerous misconception, as it creates the impression that those who demand privacy must be deviant, criminal, or wrongdoers.' - Why Privacy Matters.

    » Read more
  • There is a wonderful place to learn, or if you're stuck in the thought that there's nothing left to learn, then the comments over at Hacker News are just for you.

    Y Combinator - the company behind Hacker News focuses on venture capital investments for startups in Silicon Valley, so it’s no surprise that there are many brilliant minds commenting here. But their casual discussions provide us with keywords that can open up many new insights.

    Don't believe it? Just scroll a bit, click on a post that matches your interests, check out the comments, and don’t forget to grab a cup of coffee next to you ☕️

    » Read more
  • Just got played by my buddy Turso. The server suddenly crashed, and checking the logs revealed a lot of errors:

    Operation was blocked LibsqlError: PROXY_ERROR: error executing a request on the primary

    Suspicious, I went to the Turso admin panel and saw the statistics showing that I had executed over 500 million write commands!? At that moment, I was like, "What the heck? Am I being DDoSed? But there's no way I could have written 500 million."

    Turso offers users free monthly limits of 1 billion read requests and 25 million write requests, yet I had written over 500 million. Does that seem unreasonable to everyone? 😆. But the server was down, and should I really spend money to get it back online? Roughly calculating, 500M would cost about $500.

    After that, I went to the Discord channel seeking help, and very quickly someone came in to assist me, and just a few minutes later they informed me that the error was on their side and had restored the service for me. Truly, in the midst of misfortune, there’s good fortune; what I love most about this service is the quick support like this 🙏

    » Read more

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.

Premium
Hello

5 profound lessons

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

Every product comes with stories. The success of others is an inspiration for many to follow. 5 lessons learned have changed me forever. How about you? Click now!

View all

Subscribe to receive new article notifications

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

Comments (1)

Leave a comment...
Avatar
Anh Đức2 years 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ống2 years 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