How I Setup ESLint, Prettier, and EditorConfig for Static Sites
Tags: eslint, prettier, setup, guide
Published: 2022-01-25 06:52:20

Whenever I build simple static sites, I always find the need to set up ESLint, Prettier, and EditorConfig. These tools help with linting and formatting the code I write to follow better code standards and best practices. Each tool has its benefits and they can all work together to provide great flow when writing code.

`ESLint` - helps with analyzing my code and pointing out potential issues and best practices to follow to encourage better coding patterns

`Prettier` - helps with auto-formatting my code based on custom configurations I have set for the codebase

`EditorConfig` - helps with customizing my editor to enforce consistent styling for the codebase

All 3 of these tools are somewhat similar and they do overlap at times. This makes it very confusing for developers to know how to properly set them up. Honestly, there are times when I still get confused on what configuration to change to handle certain issues, that's I created this guide as a reference for myself and other developers to follow a standard setup guide when building a static website.

---

## Table of Contents
  - [Prerequisites](#prerequisites)
  - [Setup Project & Initialize NPM](#setup-project-and-initialize-npm)
  - [How To Set Up ESLint](#how-to-set-up-eslint)
  - [How To Setup Prettier](#how-to-setup-prettier)
  - [EditorConfig](#editorconfig)
  - [Auto Lint and Format On Commit with Husky](#auto-lint-and-format-on-commit-with-husky)

---

## Prerequisites

> Before we get started, make sure you have latest version of Node.js installed along with VSCode and Terminal:
  - [Node.js](https://nodejs.org/en/download/) (^12.22.0, ^14.17.0, or >=16.0.0)
  - [Visual Studio Code](https://code.visualstudio.com/download)
  - [iTerm](https://iterm2.com/downloads.html) / Terminal

---

## Setup Project and Initialize NPM

Create a new directory for your project:
```bash
mkdir <PROJECT_NAME>
cd <PROJECT_NAME>
```

Initialize NPM in it:
```bash
npm init
```

![NPM Init](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5sfyeoujyz3579467k6g.png)

---

## How To Set Up ESLint

Install ESLint package from NPM as a dev-dependency 
```bash
npm install eslint --save-dev
```

![Install ESLint](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/roggcns4zkou5q5k65f6.png)
 

Setup an ESLint configuration file
```bash
npm init @eslint/config
```

Running the command above will walk through a list of questions to set up an ESLint configuration file. Since we are mainly concerned with handling a simple static website with HTML, CSS, and JavaScript files, we will keep it simple.

> ESLint should check syntax, report problems, and enforce a popular coding style 
> 

![ESLint Check Syntax, Find Problems, Enforce Code Style](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2pu65r32b6wmy8rcmue7.png)

> Let's go with JavaScript ES Modules
> 

![ESLint Check Syntax, Find Problems, Enforce Code Style](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ccqel6sn5yu2g4l25bj.png)
 

> We won't be using any framework as we are building a simple static site
> 

![ESLint No Framework](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/57lmcy2gj419rn4oqnai.png)
 

> No TypeScript either, but if you want to use it, select "Yes"
> 

![ESLint No TypeScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z3pctinl27weu8llo4fw.png)
 

> Our code will only be executed on the browser
> 

![ESLint Runs On Browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/of8n2acrnz0xeimf7r27.png)
 

> We will use a popular style guide to enforce a set of coding standards
> 

![ESLint Use Style Guide](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sgeq5cor6woi6r2s2uip.png)
 

> We will go with Airbnb's style guide as it is a common choice for most open source projects
> 

![ESLint Use Airbnb Style Guide](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p221jdxp66xan7yg23wa.png)
 

> Save ESLint configuration file as a JavaScript file 
> 

![ESLint Format JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6d0gqgscjcqyi9xeonlm.png)
 

> Since we are using Airbnb's style guide, we'll need to install a few more dependencies
> 

![ESLint Install Dependencies](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5axhv7c36rmrk3b74lb.png)
 

That's it! Now, we should have a `.eslintrc.js` file created on the root of the project...

```js
// .eslintrc.js

module.exports = {
  root: true,
  env: {
    browser: true,
    es2021: true,
  },
  extends: [
    'airbnb-base',
  ],
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module',
  },
  rules: {
  },
};
```

Now, let's install the [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) extension for VSCode. This extension is crucial as it highlights potential syntactical issues on the VSCode editor as we write code.

Create a `.eslintignore` file to ignore linting on certain files or directories
```js
// .eslintignore

node_modules
```
We'll include `node_modules` in here to specifically tell ESLint to not run any linting in it as it is not part of our code.

Finally, let's setup a `lint` script inside package.json to check for ESLint errors from the command line
```json
"scripts": {
  "lint": "npx eslint ./"
},
```

With this setup, now we can run `npm run lint` to ask ESLint to spit out any potential errors it finds within our entire project directory

Alright, that's all we need for ESLint. Let's jump to Prettier!

---

## How To Setup Prettier

First, install the Prettier package from NPM as a dev-dependency:
```bash
npm install --save-dev --save-exact prettier
```

Setup Prettier configuration file by creating a `.prettierrc.json` file on the root level

```json
{
  "trailingComma": "es5",
  "tabWidth": 2,
  "semi": true,
  "singleQuote": true
}
```

These are just a few sane defaults I use, feel free to customize more options from this exhaustive [list](https://prettier.io/docs/en/options.html).

Now, install the [Prettier - Code formatter](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) extension for VSCode. Similar to the ESlint extension, this one is also super useful. Why? because it will automagically format your code as you make changes to it!

Let's set up VSCode to format our code on save:

> On VSCode, go over to `Settings` from the bottom left corner

![VSCode Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h0lp2xkp2xtwd6fuh6k.png)
 

> Then, type in `format` on the search setting input (up top)

![VSCode Format On Save](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68ejryh5efzew5jgj5y1.png)
 

- Ensure `Editor: Default Formatter` => `Prettier - Code formatter`
- Ensure `Editor: Format On Paste` checkbox is checked
- Ensure `Editor: Format On Save` checkbox is checked 


We can also setup a `.prettierignore` file to ignore auto formatting on certain files or directories
```js
// .prettierignore

node_modules
```

Finally, let's set up a `format` script inside `package.json` to auto-format all of our project files from the command line:
```json
"scripts": {
  "format": "npx prettier --write ."
},
```

With this setup, now we can run `npm run format` to instruct Prettier to auto-format all the files within our entire project directory.

>**Important!**
Let's pause for a bit... our Prettier configuration is now all set and should be working, but there is a hidden problem. ESLint comes with a few default formatting rules out of the box that may collide with Prettier formatting rules. So, to get around it, we need to override those specific ESLint rules in favor of Prettier because Prettier deals with all formatting rules. 

Let's go ahead and implement the prettier override...

Install the `eslint-config-prettier` package from NPM, 
```bash
npm install eslint-config-prettier --save-dev
```

This package disabled all ESLint rules that overlap with Prettier, so to enable the prettier rules, add "prettier" to the end of the `extends` array inside `.eslintrc.js` file...
```js
extends: ['airbnb-base', 'prettier'],
```

Now, we should be all good! Prettier should work together with ESLint to enforce coding standards and formatting rules at the same time.

---

## EditorConfig

While Prettier mostly takes care of code formatting, EditorConfig can enforce additional restrictions on a developer's editor. In some cases, Prettier can also use EditorConfig configurations to auto-format our code as well if, (1) `.prettierrc` file is not provided and (2) the Prettier VSCode extension is already installed.

Let's create a `.editorconfig` file on the root level of our project:

```yml
root = true

[*]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 2
trim_trailing_whitespace = true

[*.md]
trim_trailing_whitespace = false
```

For additional configuration, feel free to use the exhaustive [list](https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties)

---

## Auto Lint and Format On Commit with Husky

Husky is a great tool that enables us to integrate certain actions on Git hooks. This can come in handy for us when it comes to linting and formatting our code. As developers, we try to automate most of our repeated actions as much as possible. Here, we'll try to auto-lint and format our code on commits.

First, install husky from NPM as a dev-dependency:

```bash
npm install husky --save-dev
```

Let's also initialize git inside ou project as well:
```bash
git init
```

Then, run: 
```bash
npx husky install
```

After that, add a commit hook:
```bash
npx husky add .husky/pre-commit "npm run lint && npm run format && git add ."
git add .husky/pre-commit
```

Now, whenever you commit any changes, it will first run `npm run lint` and `npm run format` as a pre-commit action. This will ensure that all your code is linted and formatted before it is committed to source control.

---

*Before I leave, a few things…*

- 📑 bookmark this page in case you want to refer back to it later on
- 👍 share this article with your peers or anyone who might need help setting up ESLint, Prettier, and EditorConfig
- 💌 if I got anything wrong in this article, please leave a kind feedback

*Resources:*
- https://blog.theodo.com/2019/08/empower-your-dev-environment-with-eslint-prettier-and-editorconfig-with-no-conflicts/
- https://betterprogramming.pub/comparing-the-top-three-style-guides-and-setting-them-up-with-eslint-98ea0d2fc5b7
- https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties
- https://www.npmjs.com/package/husky
- https://eslint.org/docs/user-guide/getting-started
- https://codeburst.io/eslint-everything-you-need-to-know-about-enforcing-a-style-guide-with-eslint-d4520c732dcb
- https://seeklogo.com/vector-logo/397338/editorconfig
- https://github.com/spencerdcarlson/husky-elixir
- https://freebiesupply.com/logos/eslint-logo/
- https://prettier.io/