ESLint: The Next-Gen JS Linter

ESLint: The Next-Gen JS Linter

·

8 min read

Quick Summary~

One day I was scrolling YouTube, and I was introduced to a YouTube video talking about how to make your JavaScript code better and error-free.

My mind blew up🤯 and I clicked the video, and then I got to know about ESLint from it.

Then I opened VSCode and downloaded the ESLint extension.👇🏼

Then I came to know that there's a way to automatically detect incorrect patterns.

đź’ˇThe "ES" in the ESLint is "Ecmascript"- Javascript Standard, being more popular after Ecmascript-6.

Legacy Problems

You might be looking at some code from old projects and thinking about errors in syntax or inconsistent styles.

How ESLint can guide you through this coding maze is as follows:

Start with a Baseline Configuration:

Make a baseline ESLint configuration for the project before starting to refactor. Without bombarding you with too many warnings, this configuration should concentrate on identifying serious problems.

npx eslint --init

Gradual Rule Adoption

Attempting to fix all ESLint issues at once can be overwhelming, especially in a large legacy codebase. Instead, enable additional rules incrementally.

// .eslintrc.js
module.exports = {
  // ...
  rules: {
    'no-console': 'error',
    'semi': ['error', 'always'],
    // Enable more rules as you go
  },
};

Use .eslintignore for Exclusions

In a legacy codebase, there might be certain files or folders that are not immediately relevant to your cleanup efforts. You can use a .eslintignore file to exclude these from ESLint checks.

plaintextCopy code# .eslintignore
node_modules/
dist/

Auto-fix

ESLint can automatically fix many issues for you with the --fix option

npx eslint --fix your-file.js

Get Started

Let's start learning by getting the whole process from Installation to initial configuration, it can take a significant amount of time just to get those first linting results to show up and be useful.

You can install ESLint from npm by typing:


$ npm install eslint

OR

If you want to install eslint globally


$ npm install -g eslint

Before linting for the first time, the majority of linters require you to manually go through and set up configuration options. To do this, you might have to sift through the documentation to determine which rules to use. While you might eventually want to do that, ESLint can walk you through the fundamentals of initial configuration setup. Change to the directory containing the files you wish to lint, then type.


$ eslint --init

You will be asked to answer some questions:

$ eslint --init
? What style of indentation do you use? Tabs
? What quotes do you use for strings? Double
? What line endings do you use? Unix
? Do you require semicolons? Yes
? Are you using ECMAScript 6 features? Yes
? Where will your code run? Browser
? Do you use JSX? No
? What format do you want your config file to be in? js
Successfully created .eslintrc file in c:\Users\Nicholas\projects\personal\tmp

The eslint –init process sets up an ESLint configuration file, .eslintrc, in the current directory. ESLint uses this file to determine which rules to apply when evaluating your code. Configuration files can be in JSON format or css, and we find most users prefer css.

After that, you can start linting files by passing in one or more filenames or directories:


$ eslint test.js src/

Configuration Files

Configuration files are what make ESLint so flexible.

You can specify certain rules in the file:
Rules you want to run on files

  • Global variables that should be present in files

  • Environments in which files run

  • A base configuration to inherit

  • Plugins to load

  • Alternate parsers to use

It can be viewed as


rules:
  indent:
    - 2
    - tab
  quotes:
    - 1
    - double
  linebreak-style:
    - 2
    - unix
  semi:
    - 2
    - always
env:
  browser: true
extends: 'eslint:recommended'

This example credit goes to Blog on Smashing Magazine

This file's rules section, which describes rule settings, is the first section. The terms semi, linebreak-style, quotes, and indent all refer to ESLint rules. The rule severity is the first item in an array that is configured for each rule. One of three values makes up the rule severity:

0: completely disable the rule.

1: make the rule a warning.

2: make the rule an error.

Understanding The Output

The default formatter for ESLint output, designed by Sindre Sorhus, is another great example of how ESLint works hard to be useful to users. Here’s some example output:


$ eslint test.js

test.js
  1:11  error    Expected linebreaks to be 'LF' but found 'CRLF'  linebreak-style
  2:1   error    Unexpected console statement                     no-console
  3:9   warning  Strings must use doublequote                     quotes

âś– 3 problems (2 errors, 1 warning)

The results for each file are separated out with a header (in this case, test.js) and then each error and warning is listed beneath with four pieces of information:

  1. The line number and column number that triggered the rule

  2. The rule severity (error or warning)

  3. The message

  4. The rule that generated the message

We’ve found that all of this information is key to helping developers understand what to fix. In JSLint and JSHint, it’s hard to know how to eliminate a message (which gave rise to the JSLint Errors site). With ESLint, the rule to configure is right there in the output.

ESLint also ships with other formatters designed to make integration with other tools easy. And because ESLint is all about extensibility, you can also create and distribute your own formatters.

Plugins

As mentioned previously, one of ESLint’s original goals was to enable developers to write their own custom rules and plug them in at runtime. ESLint accomplishes this through plugins. An ESLint plugin can contain any number of custom rules that can then be distributed and used.

For instance, eslint-plugin-react is a popular ESLint plugin that has additional rules specifically targeting the React library. To use eslint-plugin-react, you must first install it via npm:


$ npm install eslint-plugin-react --save-dev

Then, in your configuration file, you indicate that eslint-plugin-react should be loaded by using the plugins array. After that, you can configure individual rules inside the plugin just like you would any other ESLint rule:


plugins:
  - react
rules:
  react/display-name: 2
  indent:
    - 2
    - tab
  quotes:
    - 1
    - double
  linebreak-style:
    - 2
    - unix
  semi:
    - 2
    - always
env:
  browser: true
ecmaFeatures:
  jsx: true
extends: 'eslint:recommended'

You can safely omit the eslint-plugin- prefix when using a plugin name in the configuration file, so just react is enough to identify the plugin. The rule react/display-name is set to be an error. The react/ prefix lets ESLint know that this rule is from a plugin rather than the core.

There are over 80 ESLint plugins published to npm, and many that teams use internally at their own companies. Anyone can create their own custom rules and the ESLint Yeoman Generator to guide you through the process.

Custom Parsers

Another way you can customize ESLint is by specifying custom parsers. By default, ESLint uses the Espree parser (a fork of Esprima) that provides ECMAScript 6 and JSX support natively. However, ESLint can use any parser that generates an ESTree-compatible AST. It’s this capability that led ESLint to be the first linter to support Babel through the use of babel-eslint.

The babel-eslint parser is an adapter that makes Babel output an AST format that ESLint can understand. As a result, using babel-eslint means that ESLint can understand and work with almost every experimental syntax that Babel supports (there are, of course, some compatibility issues when dealing with experimental features). To use babel-eslint, first install it:


$ npm install babel-eslint --save-dev

Then specify the parser key in your configuration file:


parser: babel-eslint
rules:
  react/display-name: 2
  indent:
    - 2
    - tab
  quotes:
    - 1
    - double
  linebreak-style:
    - 2
    - unix
  semi:
    - 2
    - always
env:
  browser: true
ecmaFeatures:
  jsx: true
extends: 'eslint:recommended'

When ESLint runs using this configuration file, it will swap in babel-eslint for Espree when it parses your code.

Decoupling the linter from the parser is one of the significant innovations in ESLint that has allowed us to move quickly to support a wide variety of use cases.

Linting Improvements

Linters have traditionally worked in the same way: figure out a list of files to lint, lint each file, then report the results. The ESLint team, however, is always looking for ways to make the linting experience more effective and efficient. Recently, the team added a couple of new features that really emphasize just how powerful ESLint is:

  • The --fix command line option tells ESLint to attempt to automatically fix as many problems as possible. Fixes are only applied when it is safe to do so, and you’ll see any problems that were left unfixed. So now instead of going back into your files to insert a missing semicolon or properly indent some code, ESLint can do it for you. This is especially useful when you first introduce ESLint into a project as it means you don’t have to manually fix every file.

  • The --cache command line options tells ESLint to keep track of files that had no problems so that future runs will only lint files that have changed. If you’re repeatedly running ESLint over a large codebase, this can save you a lot of time.

Hope you loved the blog.
Don't forget to follow me.

Thanks

Â