Master ESLint in 7 Minutes

Matthew Bub
Webtips

--

Nobody likes spaghetti code. The Array with inconsistent quotations for a lack of better purpose is hardly acceptable and the console riddled with “hi” will certainly appear amateurish, if not unfinished at best.

Clearly, I am a good practices advocate, but with a good cause. No matter the level of seniority, if you plan on making your way to the job market in 2021 and beyond you will surely compete with someone who took the time to enforce a style guide.

Table of Contents

What is a Style Guide in Software Development?

From a design standpoint, this is generally a document with a series of rules and guidelines the designer must abide by. These documents generally cover topics such as colors, fonts, spacings etc. Now let’s tie this concept into software development.

“With a language as forgiving as JavaScript, and the collective minds of multiple independent thinkers, there will surely arise a conflict of style.”

Me

A style guide in software development is essentially a document with a series of rules and guidelines that developers must abide by.

But who will be there to enforce this set of rules? Surely with a language as large as JavaScript, there would be thousands of rules to enforce, which is an off putting thought... And as it turns out, there is.

Lucky for us it is 2021 and the heavy lifting has been done for us. Tools such as ESLint and Prettier can help establish, maintain and enforce consistency amongst source code. Essentially a style guide for developers. Below I’ve detailed how we can take advantage of ESLint with Node.js.

Warning: If you’ve never worked with a linter that is fine, DO NOT GET DISCOURAGED if your code returns numerous lint errors. It’s totally normal.

Getting Started with ESLint

If you haven’t already, go ahead and initialize a new node.js project so we can install the devDependencies we will be using for this workflow. If using Git, don’t forget to ignore node_modules .

$ npm i eslint -D

For this walkthrough, I will be using the Airbnb Style Guide, which is a plugin for ESLint with a designated set of rules and guidelines that the team over at Airbnb have turned into their standard for writing JavaScript code.

You don’t have to follow these prompts exactly, and whether or not you use the Airbnb Style Guide will not affect what we are doing here. That being said, use your own thought process and decide for yourself which options best suit your needs.

Create the ESLint Config

$ npx eslint --init

Let’s take a look at our directory structure by running ls from within the terminal. We should see something like this in our current working directory.

workspace
├── node_modules/
├── .eslintrc.js
├── package-lock.json
└── package.json

If you chose the Airbnb Style Guide with both browser and node compatibility, your .eslintrc.js file will probably auto-generate to look something like this:

module.exports = {
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'plugin:react/recommended',
'airbnb',
],
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 12,
sourceType: 'module',
},
plugins: [
'react',
],
rules: {},
};

If your configuration needs additional dependencies, ESLint should prompt you. If you think you’ve missed something you can always run the npx eslint --init command again.

...
"devDependencies": {
"eslint": "^7.17.0",
"eslint-config-airbnb": "^18.2.1",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-jsx-a11y": "^6.4.1",
"eslint-plugin-react": "^7.22.0",
"eslint-plugin-react-hooks": "^4.2.0",
"prettier": "^2.2.1"
}

Note: technical debt will pile up quickly for an unfamiliar style guide. If you use VSCode, it’s worth mentioning you will probably want to install the ESLint extension to assist with lint errors as you go.

Working with ESLint

Like I’ve mentioned above, the easiest way to work with ESLint in my opinion, is with the ESLint extension for VSCode. We won’t be diving into the details of this extension, just know that it provides helpful syntax highlighting and descriptive error/ warning messages.

Let’s create an index.js file with some starter code with the intention of breaking the linter.

// sloppy code
var hello = name => { return "Hello, " + name + "!" }
console.log(hello("World"));

Now if we log this response we get “Hello, World!” which is great. But remember when I said JavaScript is a forgiving programming language? Let’s run ESLint from the terminal and see how this basic function can be improved according to the Airbnb Style Guide.

$ npx eslint --cache index.js

Wow, 11 problems. What on earth happened? Did we break it? Nope. The Airbnb style guide is letting us know where we can improve, and like all things this will become easier in time.

Debugging ESLint Errors

It would be advised to read through these one-by-one until you become familiar. But for now let us run ESLints --fix command to resolve as many errors as we can.

$ npx eslint --fix index.js

Our code has now been formatted to abide by the Airbnb style guide.

// formatted to AirBnb style guide
const hello = (name) => `Hello, ${name}!`;
console.log(hello('World'));

Now if we run our linter again we will be presented with only a warning. Unexpected console statement which again, in my opinion, is a good warning to have. However there will be times that will arise when we need console.logs in production, an example could be a terminal-based application. So how can we resolve this issue? Well, ESLint gives us 3 options to resolve errors and warnings, you can decide the best use case for your particular scenario:

Ignore ESLint warnings/ errors for this line only

Add a comment to the line directly above the problem in the format // eslint-disable-next-line <WARNING/ERROR>

// eslint-disable-next-line no-console
console.log(hello('World'));

Ignore ESLint warnings/ errors warning for the entire file

Add a comment to the top of the file in the format /* eslint-disable <WARNING/ERROR> */

/* eslint-disable no-console */
...
console.log(hello('World'));

Ignore ESLint warnings/ errors for the entire project

Sometimes we will need to disable specific rules for the entire project. To handle these case’s we can head to the ESLint config file we created earlier. Here we can manage rules throughout the entire project.

... 
rules: {
'no-console': 'off'
},

You can learn more about ESLint rules and options here. But rest assured that all ESLint errors are easily searchable online. As a last step for our ESLint config, let’s add the commands we’ve already used above to our package.json

...
"scripts": {
"lint:js": "eslint --cache \"**/*.{js, jsx}\"",
"lint:fix": "eslint --fix \"**/*.{js, jsx}\""
}

Note: adding scripts is not only great for shorthand reference, they are also key for collaboration.

Congratulations and good job! We have successfully configured ESLint in our workflow. Now there are tons of additional utilities we can add to assist ESLint such as Prettier, Husky, and lint-staged. Perhaps we’ll dive into those next time.

View the Source Code for this Walkthrough here. (Don’t forget to star! ⭐)

If you’ve found this content useful or have suggestions for improvement, let me know! Thanks for your time. — Matthew Bub

TLDR

$ npm i eslint -D && npx eslint --init
...
"scripts": {
"lint:js": "eslint --cache \"**/*.{js, jsx}\"",
"lint:fix": "eslint --fix \"**/*.{js, jsx}\""
}

--

--