Linting in Node.js using ESLint

A linter is a computer program that analyzes and checks source code. It flags programming errors, indentation errors, formatting errors, bugs, and suspicious constructs.

1. Introduction to Linting

Linters are tools that perform static code analysis in software testing.

Static Code Analysis is the analysis of computer software that is performed on static code. It is performed by looking at source code without running it. This process is usually done using a software or an automated tool. Static Code Analysis is done as a part of the programming phase in a typical software engineering workflow.

Linters scan source code and flag code blocks that violate rules. These rules can be aesthetic styling rules, syntactic rules, etc… Linters provide options to define rules or import style guides through a config file.

2. Advantages of a Linter

  • Linters catch mistakes while writing code.
  • They stop mistakes from happening earlier and reduce time used by debugging.
  • It reduces costs since critical errors are caught before deployment.
  • Helps enforce a style guide across a project, to keep code consistent. This is done by the use of a config file.
  • Code reviews are sped up, since basic issues are fixed by the linter.

3. ESLint and Node.js

Let us now set up ESLint with Node.js to improve code quality in our projects.

First, initialize a Node.js project.

npm init

Now, install the eslint npm package.

npm i --save-dev eslint

In order to initialize an ESLint configuration, let us run the command.

./node_modules/.bin/eslint --init

This will bring up the ESLint initial setup. The program gives us choices to set up an initial configuration.

  • How would you like to use ESLint? – To check syntax, find problems and enforce code style
  • What type of modules does your project use? – JavaScript Modules (import/export)
  • Which framework does your project use? – None of these
  • Does your project use TypeScript? – No
  • Where does your code run? – Node.js
  • Would you like to use a style guide for your project? – Use a popular style guide. (Select the Google Style Guide)
  • What format do you want your config file to be in? – JSON

ESLint is installed as a developer dependency. Now, let us check the working of ESLint. Create a file called index.js, and enter the following code.

const express = require("express")

The code above is analyzed by ESLint and throws the following errors.

ESLint Error

This error is because it isn’t good practice to declare and assign a variable and not use it.

ESLint Error

The Google Style Guide recommends the use of single quotes.

ESLint Error

It is good practice to use semi-colons at the end of a line.

Now, to fix the errors we can set up ESLint to automatically fix errors when we save the file. In Visual Studio Code, go to Settings -> Workspace and search for save

VSCode Settings

There will be an option, Editor: Code Actions on Save. Click on Edit in settings.json and enter the following config.

{
    "editor.codeActionsOnSave": {
      "source.fixAll.eslint": true
    },
    "eslint.validate": ["javascript"]
}

Save the file and you’re good to go! Whenever we click on save, ESLint will automatically fix the errors in our project.

4. Airbnb Style Guide

style guide defines rules and conventions on how code should be written and organized. Style guides help to maintain a common standard for writing code in projects.

The Airbnb JavaScript Style Guide is a set of standards launched by Airbnb. It is based on the standards prevalent in JavaScript with some modifications.

To install the latest Airbnb style guide in ESLint,

npx install-peerdeps --dev eslint-config-airbnb

This installs the config as a peer dependency.

Now, we should extend the style guide in our ESLint Configuration. In .eslintrc.json,

{
    "extends": [
        "airbnb"
    ],
 }

You project will be analyzed according to the Airbnb Style Guide.

5. Further Reading

Related posts:

Making a Discord Bot (With Node.js)
Keeping Node.js Fast: Tools, Techniques, And Tips For Making High-Performance Node.js Servers
Building A Pub/Sub Service In-House Using Node.js And Redis
Implementing Caching in Node.js using Redis
An Absolute Beginner Guide to Node Package Manager
Sharing Code Between Projects: Lessons Learned In The Trenches
Writing A Multiplayer Text Adventure Engine In Node.js: Adding Chat Into Our Game (Part 4)
How to use TypeScript with Node.js
Building your First Telegram Bot using Node.js and Telegraf
Rendering HTML Pages as an HTTP Server Response Using Node.js
Writing A Multiplayer Text Adventure Engine In Node.js: Creating The Terminal Client (Part 3)
Testing Node.js Applications
JavaScript Particles Effect with tsParticles
Most Useful Node.js Packages
Building a RESTful Web API in Node.js using PostgresSQL and Express
How to Consume a Co-operative Bank API using Node.js
Node.js vs Python for Backend Development
Data Encryption and Decryption in Node.js using Crypto
Node.js CLI Input
Implementing Lipa na Mpesa Online using Node.js
How To Develop A Chat Bot With Node.js
Why Static Typing & Why is TypeScript so popular?
Building a Simple Cryptocurrency Blockchain using Node.js
Debugging a Node.js app running in Docker using Nodemon and the Docker extension
Building A Node.js Application Using Docker
How To Auto-generate Admin Panels for Node.js with AdminBro
Getting Started with Node.js Paypal Checkout Integration
Web Scraping With Node.js
Getting Started with Node.js REPL
Analyzing Your Company’s Social Media Presence With IBM Watson And Node.js
How To Build and Test a Node.js REST API with Express on Ubuntu 18.04
Creating A Continuous Integration Test Workflow Using GitHub Actions