Open CheatSheet Back To List

ESLint (Video Tutorial)

ESLint

Intro

[0:00 Video timestamp] 

ESLint is an open source project that helps you find and fix problems with your JavaScript code.
This tutorial goes over how to install and configure ESLint, select a style guide, how to view rules and rule options, how to add or modify rule, install and use the ESLint plug-in for VS Code, and disable specific rules in your code. 

The ESLint website is at: eslint.org

Node.js: Before getting started, you must have Node.js installed.
To see of Node.js is installed on your computer, open the Terminal and enter: node --version.
If that command throws an error instead of returning the Node version then you need to install Node.
Download and install the LTS version from their website: nodejs.org
The Node Intro tutorial includes installation instructions: learnbycheating.com/subjects/nodejs/node-introduction

Finished Example Code: The code and steps are provided in the tutorial. The ending code is available for reference at github.com/LearnByCheating/eslint-demo.

Read it, watch it, do it, review it: The tutorials on this site follow the read it, watch it, do it, review it pattern.

Read it: This is the written version of the tutorial. There is an accompanying video version that demonstrates the steps taken. There are timestamps below the headings that align to the timestamps in the video.
Watch it: After reading a topic, view the video version to get a visual representation of the steps. 
Do it: After reading and watching a topic, follow the steps in your own code.

Review it: When you are done with the whole tutorial, open the CheatSheet and review the ES Lint category. Make sure you understand everything, and can refer back to the CheatSheet when you are working on your own projects in the future. 



JavaScript Style Guides

Syntax errors: JavaScript has some syntax rules that must be followed or errors will occur.

Style choices: But there are also many syntax choices that are a matter of preference. For instance:
  • Semicolons: If you omit semicolons from the end of your statements, the JavaScript engine will automatically insert them when parsing your code. Although, there are some specific cases where it won't. Some JavaScript developers have opted to only use semicolons in the specific cases where they will not be automatically added. Is it okay to omit semicolons? That's a matter of opinion since there is no official ECMAScript style guide. In fact, the answer is it doesn't really matter as long as you, or your team are consistent.
  • Single or double quotes: Strings can be declared using single or double quotes. Which should you use? Again, it doesn't matter, but it's best if you or your team are consistent about it.

There are some companies and individuals that have published style guides internally, and made them available to the general public.
The most popular ones include:

The AirBnB and Google style guides mostly agree, which is a good confirmation on those rules. In the tutorial, we will use the AirBnB style guide.



Add ESLint to a project

[0:06 Video timestamp]

  • Create a Node.js project:
    • Create a project folder named eslint-demo. 
    • Add a file to it named app.js and populate it with the below JavaScript code. It contains some errors and style problems.
app.js
/*
  Click squiggly lines to see the rule that is violated, and the options to fix or disable the rule for the line or the entire file.
*/

const double = (num) => {
  let res = num * 2;
  return res; 
}
const res = duble(10);
console.log(`Function result: ${res}`);

  • package.json file: Add a package.json file to the project so you can add the ESLint npm package to it. 
    • In the Terminal, from the project root directory enter the npm init command with the --yes option to use the default values: 
      • npm  init --yes 
    • Or just create a simple one manually:
package.json
{
  "name": "eslint-demo",
  "main": "app.js"
}

  • Then install the eslint npm package: 

  • It will ask a series of questions. Below is the configuration used in the Video tutorial:

    • How would you like to use ESLint? Select: check syntax, find problems and enforce code style. 
    • What type of modules does your project use? We aren't using modules in this simple example so it doesn't matter what you select. 
      • If you were using import/export statements then select JavaScript modules (import/export).
      • If you were using require methods then select CommonJS (require/exports)
    • What Framework does your project use? None
    • Does your project use TypeScript? No
    • Where does code run? Your options are Browser, Node, or a for all. Select all
    • How would you like to define a style for your project? Select Use a popular style guide.
      • A list of the four most popular style guides will appear. For this tutorial, select AirBnB
    • What format do you want your config file to be in? JavaScript, YAML, or JSON. Select JSON
    • Next it asks if you want to install the AirBnB config package and an import plug-in: Yes
    • Which Package Manager do you want to use? Select npm

  • Now the eslint, eslint-config-airbnb-base, and eslint-plugin-import packages will be installed as development dependencies.
  • The package names will appear in the package.json file, and the package code will be loaded in the node_modules folder.
  • A configuration file named .eslintrc.json was added to your project with the configuration we just entered. 



Run ESLint from the Terminal

[2:13 Video timestamp]

  • Let's run ESLint against our app.js file. Clear the Terminal: clear
  • The ESLint package executable is installed in node_modules/.bin/eslint
  • To run it on a specified file, in the Terminal enter the path to the eslint executable followed by the relative path to the file you want to lint:
    • node_modules/.bin/eslint app.js
  • That will run the linter and print a list of the errors and warnings from the file in the Terminal:




VS Code ESLint Extension

[2:42 Video timestamp]

  • Visual Studio Code has a better way to view the errors if you add the ESLint Extension.
  • To install the ESLint extension, click the Extensions button on the Activity Bar: 
  • Type in "ESLint". When it appears click the install button.

  • Now if you go back to the app file, you'll see the ESLint rules were applied to the code.
    • Errors are indicated with squiggly red underlines.
    • Warnings are indicated with squiggly yellow underlines.



Problems Panel

[3:58 Video timestamp]

  • When the ESLint extension is installed, problems will be printed in the Problems panel.
  • To open it from the Terminal panel, click the Problems tab.
  • Each problem shows:
    • Whether it is an Error or Warning. 
    • What the problem is. 
    • The rule name which links to the rule's web page documentation.
    • And what line and column the problem is on.




.eslintrc.json configuration file

[3:11 Video timestamp]

  • When you added ESLint to the project it generated a configuration file called .eslintrc.json. The configuration is based on the questions you answered during installation.

.eslintrc.json
{
    "env": {
        "browser": true,
        "commonjs": true,
        "es2021": true,
        "node": true
    },
    "extends": "airbnb-base",
    "overrides": [
    ],
    "parserOptions": {
        "ecmaVersion": "latest"
    },
    "rules": {
    }
}

  • The environment (env) property indicates the JavaScript environment (browser and node), type of modules (commonjs), and version of JavaScript (es2021).
  • The extends property is where we assign the AirBnB style guide rules to the linter.



Set or modify rules

[4:14 Video timestamp]

The full list of available ESLint rule names and options can be found at: eslint.org/docs/latest/rules

With the ESLint plugin installed, problems are indicated directly in your JavaScript files.
  • Errors are indicated with squiggly red underlines.
  • Warnings are indicated with squiggly yellow underlines.

To find out what rule is being violated:
  • Click the squiggly underlined code, then click the lightbulb that appears.
  • A list of options will appear. Click Show documentation for rule 
  • Selecting this option will open a web page displaying the rule's documentation.

Open the ESLint configuration file. To add new rules or modify the style guide's rules, add them to the rules object. Add the below and we will explain what we did:
.eslintrc.json
{
    ...
    "rules": {
        "no-console": "off",
        "no-unused-vars": "warn",
        "max-len": ["error", { "code": 100, "ignoreComments": true }] 
    }
}

In the rules object, add the rule you want to change as a property. Then set the severity as: error, warn, or off. 

    • "no-console": "off"
    • Console logs should generally not be used in projection so the style guide gives a warning when used in your code.
    • To turn that rule off, we changed the severity from "warn" to "off". 
    • That will remove the console.log warning we got.

  • No-unused-variables:
    • The rule and option documentation is at eslint.org/docs/latest/rules/no-unused-vars
    • "no-unused-vars": "warn"
    • There is no point in declaring a variable if we aren't going to use it. You could treat that as a warning though, instead of an error. We changed severity from "error" to "warn". The double function was defined but never used. 
    • Now it is underlined in a yellow squiggly line instead of red. 

    • "max-len": ["error", { "code": 100, "ignoreComments": true }]
    • Our comment at the top of the file exceeds the max-len (maximum length) rule of 100 characters.
    • Looking at the documentation shows there is an option to ignore comments. 
    • To add an option you need to set the rule value to an array. 
    • The first item is the severity value. Leave it as "error". 
    • The second item is an options object. Set the ignoreComments option to true. 
    • And set the code option to 100 to keep the max length at 100 characters for non-comments. 
    • The max-len error will disappear.



Fix problems

[6:29 Video timestamp]

  • Now let's use the ESLint extension to fix the remaining problems.
  • Skip the warning (yellow underlined) for now. The first error in our code (red underlined) is a violation of the prefer-const rule. 
    • Since the res variable is never reassigned, we should declare it with const instead of let. Our code will run fine if we don't, but our style guide says to use const for variables unless you are going to reassign the value. That way if you see a variable declared with let, you will know it will be reassigned later in the code. If it is declared with const you know it will not be reassigned.
    • Click on the error, then click the lightbulb, then you'll get a list of options. The first option is to fix this perfer-const problem. Select that and "let" will be replaced with "const", and the error will disappear.
  • The next error violates the no-trailing-spaces rule. 
    • There is a trailing space on line 7.
    • To correct it click the error, then click the lightbulb, then select Fix this No Trailing Spaces problem. And the space will be removed. 
  • Next is a semi rule violation meaning a semicolon is missing. Function expressions need a semicolon at the end. Click the error, then click the lightbulb, then select "Fix this semi problem". A semicolon will be added at the end of the function expression.
  • Next is the no-undefined rule violation: "Duble is not defined". Duble is misspelled. It should be double. 
    • Click the problem in the code, then click the lightbulb. Then select Change spelling to double and save it.
    • That will correct this problem, and also the no-unused-variables warning we got.

  • Now we have no more problems left in our code.



Disable ESLint rules

[8:27 Video timestamp]

  • The last topic we'll cover is how to disable ESLint rules in your code.
  • If you remove the semicolon from line 8 you will again have a missing semicolon problem.

  • Click the problem, then click the lightbulb, and one of the options will be "Disable semi for this line".
  • Selecting that will add a // eslint-disable-next-line semi comment above the line and the rule will be ignored.
 
  • Undo that, then click the error and the lightbulb again. This time select "Disable semi for the entire file".
  • At the top of the file it will add an /* eslint-disable semi */  comment and the rule will be disabled for the whole file.

  • Undo that. You can manually disable the rule inline. Add a comment at the end of line 8: // ESLint-disable-line semi 
  • And the error will disappear. 

  • Finally, you can disable all of ESLint for the entire file by placing a /* eslint-disable */  comment at the top of the file.



Practice

Practice creating problems in your code and take the below actions until you are comfortable with how to use these features:
  • View the problems in the problems panel.
  • Click the squiggly line then view the documentation.
  • Click the squiggly line then fix the problem.
  • Click the squiggly line then disable the rule for the line or the whole file.
  • Modify the rule in the .eslintrc.json file.

Use the CheatSheet for reference so you can use it as a reference later.

Open CheatSheet Back To List