Code Quality Tooling with Prettier and ESLint

Beginner JavaScript

Enjoy these notes? Want to Slam Dunk JavaScript?

These are notes based on my Beginner JavaScript Video Course. It's a fun, exercise heavy approach to learning Modern JavaScript from scratch.

Use the code BEGINNERJS for an extra $10 off.

BeginnerJavaScript.com

Whether you are a solo developer looking to follow best practices or catch potential bugs, or you are a member of a team that has a specific way of writing JavaScript, there are many use cases for using code quality tooling.

There are two tools that are extremely helpful in code quality and formatting of your JavaScript:

  1. ESLint
  2. Prettier

Before we jump into those, let's start by looking at some code and opinions people have about formatting in JavaScript.

initial code to assess the quality of code

In the code above πŸ‘†, we are using single quotes '' rather than double quotes "", which is an opinion that some people have. Some people prefer one over the other.

The fact that there is a space between the variable name and the equal sign is actually not necessary in const p = document.querySelector('p');, that is an opinion that people have in their JavaScript. const p=document.querySelector('p'); would work the same way.

Those are just two example of things that have the potential to cause issues in your code, or are formatting preferences that people have opinions about.

The tools we mentioned earlier will help you fix those issues by either fixing it for you, or by alerting you if you are doing something that is a bad practice, or causes an accessibility issue, along with a whole lot of other things.

ESLint & Prettier

I recommend that you go to https://eslint.org and go to the demo in the navigation.

eslint homepage

For Prettier, there is a link on the homepage that says "Try it".

prettier homepage

We will cover the following about these tools:

  1. what they are
  2. how they work
  3. the steps you need to go through to install them

ESLint

ESLint, is a JavaScript linter for identifying and reporting potential issues in your JavaScript. Some examples may be bad practices or design patterns, or identifying unused variables in functions.

If you go to the ESLint demo, select the "Rules Configuration" section and choose the latest version of JavaScript.

eslint demo page with rule selector showing the list of available eslint rules such as 2015, 2016 and 2018

If you type into the demo const age = 300;, you will see the following linting rule πŸ‘‡

'age' is assigned a value but never used.

eslint demo page showing the message "age is assigned a value but never used"

If we go ahead and use it by adding a line below of console.log(age);, we will get the following errors πŸ‘‡

3:1 - Unexpected console statement 3:1 - 'console' is not defined.

One of the rules that are set in the demo version of ESLint is to not use console.log(), which is sometimes a production rule that developers use because you don't want to ship code to production that include console logs.

With ESLint, you can turn specific rules on or off. Wes will show us his own config shortly.

If you scroll down on the ESLint site, you will see a list of all of the rules that you can set using ESLint.

Sometimes as you are writing code, ESLint will throw an error and you might not know why it is being thrown. Thankfully, ESLint provides a link to the documentation of the rule so you can read through and understand what it means.

Some other things ESLint helps us with is code that is broken or confusing scoping.

Let's say you add the following code in the ESLint demo page πŸ‘‡

function hi() {
  age = 300;
}

You should get the following errors: πŸ‘‡

1:10 - 'hi' is defined but never used.

2:3 - 'age' is not defined.

If we add a let before the age variable, it will still complain that hi is defined but never used.

If we call hi(); in our code, it will complain that age is assigned but never used.

ESLint is always giving you feedback on your code.

Initially, this can be very frustrating because it tells you that all your code is wrong.

Over time, you will be able to modify your own config that fits your own coding style as well as understand as to why some of those things might be bad practices.

ESLint is also plug-able.

This means you can have many different plugins with it, there are many of them, for different styles of JavaScript, such as a React/Vue/Angular plugin.

That is a high level overview of what ESLint is. We will talk more about configuring it in just a second.

Prettier

The next tool that we have is Prettier.

Whereas ESLint will yell at you about things that are causing potential issues in your code, Prettier focuses entirely on just the formatting of your code.

Navigate to https://prettier.io/ and select the "Try me" link which should open up the playground.

Paste the following code in it πŸ‘‡

const age = 100;

alert("hey");

The output should give you:

const age = 100;
alert("hey");

prettier playground showing the output code that was formatted

The input code is technically valid JavaScript, however it is messy and harder to read. Those are annoying things, such as indentation or spaces between lines of code.

Prettier will take in all of your code.

For example if you are mixing your quotes, using single quotes ' sometimes and " double quotes at other times, Prettier will always just format the code to use one or the other, for consistencies sake, depending on the settings you have.

Prettier is pretty opinionated.

There are a few settings that we can toggle here or there, but mostly you just have to let it figure out how you want it to format you code.

You can use ESLint and Prettier separately.

What Wes likes to do is use ESLint and then use the Prettier plugin for ESLint. That way, all of his code goes through ESLint which will tell him what is wrong with his code, as well as any possible issues that ESLint can fix, including Prettier fixes, and then it will go ahead and fix those for us.

One bad thing about ESLint is after you install it, you can spent the rest of your life configuring it based on the hundreds of possible rules.

It is likely that the rules you want have already been chosen well by someone else, so often you just want to pick someone elses settings that you already like.

That is exactly what Wes did for this course.

He made a config that is a set of ESLint rules, as well as the Prettier plugin which will do the formatting for you, all bundled into one so you can hit the ground running with that config.

As you start to develop your own opinions for what you like, you can sort of overwrite those ESLint rules one by one.

Installing ESLint & Prettier

Let's get into installing Prettier and ESLint.

Go into the terminal, and use it to navigate to the beginner-javascript directory. (refer to the Welcome page if you don't have that directory).

Tip: If you don't know which directory you are currently in, type pwd in the terminal and it will return the directory that you are currently in.

There are a few things we need to do before we can get going.

We are going to follow the instructions located at https://github.com/wesbos/eslint-config-wesbos.

The ESLint config can only be installed locally per project due to changes that were made to ESLint v6 that removed global installs.

the eslint-config-wesbos repo showing the per project installation guide

Installing npm packages locally

If you don't already have your package.json, create one running the command npm init by typing it into the terminal (make sure you are in the beginner-javascript folder).

We will be talking about npm later in this course, but essentially npm allows us to download what are called dependencies, which is other people's JavaScript packages that allow us to do things. We need other people's JavaScript packages for this lesson, specifically we need ESLint, Prettier, and we need Wes' config.

Creating the package.json file

In order for that to work, we need what is called a package.json file which is going to hold a list of all of the other things in JavaScript that we need.

To create the package.json, you simply just type npm init in the terminal and press enter.

You will now be prompted to enter a package name, description, keywords, etc. but you can just press enter to skip setting those values for now.

terminal output of npm init command

Then we need to go ahead and install all of our dependencies.

Go ahead and copy this line of code and paste it in your terminal to install the dependencies.

npx install-peerdeps --dev eslint-config-wesbos

After about a minute or so, it will go ahead and install all of your packages.

terminal output after running the npx command to install the eslint-config-wesbos pacakge

If you take a look at your filesystem, you will see that there is this new folder called node_modules and inside there are a whole bunch of dependencies.

We're not going to get into what that is just yet, that will be coming in our modules lesson. For now, all we need to know is it contains all of the npm packages that makes ESLint and Prettier work.

Configuring ESLint and Prettier with VS Code

Next we need to make a new file within the beginner-javascript folder called .eslintrc. This is what is called a dot file.

Sometimes your computer will hide dot files from you because they are typically just files that developers use under the hood. Since we are developers, we do not want to hide those files.

If you have trouble seeing that file in your file system, do a quick google of "Showing hidden files Mac" or "show hidden files Windows" and it will show you how to flip that setting on.

Inside of your .eslintrc file, copy the following:

{
  "extends": ["wesbos"]
}

eslintrc file in vs code that extends the wesbos config

We are going to extend "wesbos", which means we are going to extend all the settings and plugins that Wes has packed into his own config. That is really all we need right now.

Next, what we need is to get it running with VS Code.

Scroll down in Wes' instructions to the With VS Code section.

vs code settings showing how to configure eslint

First thing you need to do is install the ESLint extension for VS Code.

Ctrl + Shift + x (cmd + Shift + x / MacOS ) will get you to the list of extensions in VS Code.

You want to search for ESLint, and you will see a whole bunch of different ones, but the one you want is just called ESLint. You'll know it's the right one because it has billions (just kidding, millions) of installs.

Go ahead and click the install button.

Now what we need to do is set up some VS Code settings. Within VS Code, in the right hand corner, navigate to Code > Preferences > Settings.

If you're on Windows, that would be File > Preferences > Settings.

vs code in MacOS showing the settings menu item

That should open up the settings section in VS Code like so πŸ‘‡

vs code ui settings page

What you want to do is click on the symbol in the top right hand corner that looks like a page with a curved arrow πŸ‘‡

the icon to open the text based vs code settings

That will open up the text based version of your settings.

vs code text settings page

Simply just copy all of the settings from Step #2 of the "With VS Code" instructions found here https://github.com/wesbos/eslint-config-wesbos.

Go to the very end of your settings.json file in VS Code, and after the last value, add a comma and then paste in the settings we just copied. (If you don't have any previous VS Code custom settings then you will have an empty object).

eslint settings in vs code that was copied from the eslint-config-wesbos github repository

Let's go through the settings really quickly.

editor.formatOnSave: true: turns on formatting on file save.

"[javascript]": {
  "editor.formatOnSave": false
}

The setting above πŸ‘† is responsible for turning off formatting on save for JavaScript. We will format JavaScript code using ESLint.

This setting below is responsible for telling the ESLint plugin to run on save. πŸ‘‡

"eslint.autoFixOnSave": true

You need to do that to prevent other built-in plugins in VS Code from clashing with our ESLint plugin.

The built-in plugin in VS Code for formatting is called Beautifier and it doesn't do as good of a job as ESLint and Prettier, so what that setting is doing is turning off the editor format on save for JavaScript and for javascriptreact and using the ESLint fix on save instead.

Finally, this is important: if you already have a prettier extension enabled, you want to disable it for JavaScript and javascriptreact using the following setting πŸ‘‡

"prettier.disableLanguages": ["JavaScript", "javascriptreact"],

Why? Because we are not using Prettier directly through the Prettier plugin. We are using Prettier through ESLint as a ESLint plugin.

This stuff can get confusing and be a real bummer, so if you get stuck or have trouble, watch the video again and check out the "troubleshooting tips" in the eslint-config-wesbos Github repository.

To check if Prettier is working, you can open a JavaScript file in VS Code and some add extra whitespace between variables and equal signs and then save the file.

If it isn't working, you can click on ESLint in the bottom corner and it will often tell you what the issues are and why it isn't workig.

vs code bottom toolbar showing the eslint icon at the bottom right

Another thing you will notice with ESLint is these squiggly underlines in VS CodeπŸ‘‡

vs code showing the eslint rule error as a red squiggle under the code

That is actually ESLint giving you information about a warning or error.

ESLint won't automatically fix these problems for us on save, it just explains what the issue is and then it's up to you to make a decision on how to solve it.

If you modified the code to be let age = 100; ESLint will give you a warning saying you used a let variable but never modify the value, maybe you want to use a const variable instead.

If you modify the code to be const age = 100;, the underline under the age variable will be yellow and the warning will say:

'age' is assigned a value but never used. eslint(no-unused-vars)

Red squiggles represent an error and yellow is just a warning.

We will be seeing that a lot during this course.

If throughout the course there is a setting you really don't like, you can go ahead and modify the .eslintrc file to disable that rule.

That works by creating a rules property like so πŸ‘‡

{
  "extends": ["wesbos"],
  "rules": {
    "no-console": 2,
    "prettier/prettier": [
      "error",
      {
        "trailingComma": "es5",
        "singleQuote": true,
        "printWidth": 120,
        "tabWidth": 8
      }
    ]
  }
}

You can set the values of the rules to:

  • 2 if you want them to error
  • 1 if you want them to warn
  • 0 if you want to ignore that rule entirely

If you get stuck, try fixing it yourself for about 20 minutes and if you are still stuck, jump into the Slack chatroom and join the #beginner-javascript channel and ask for help.

Find an issue with this post? Think you could clarify, update or add something?

All my posts are available to edit on Github. Any fix, little or small, is appreciated!

Edit on Github

Syntax Podcast

Hold on β€” I'm grabbin' the last one.

Listen Now β†’
Syntax Podcast

@wesbos Instant Grams

Master Gatsby

Master Gatsby

Building modern websites is tough. Preloading, routing, compression, critical CSS, caching, scaling and bundlers all make for blazing fast websites, but extra development and tooling get in the way.

Gatsby is a React.js framework that does it all for you. This course will teach you how to build your websites and let Gatsby take care of all the Hard Stuffβ„’.

MasterGatsby.com
I post videos on and code on

Wes Bos Β© 1999 β€” 2021