Introduction
Code consistency is king, especially when you are working in a team. The code everyone produces should follow the same rules and look consistent throughout the whole project. For this purpose there are tools like Prettier and ESLint.
ESLint
ESLint analyses your code and helps identifying and fixing problems.
Prettier
Prettier is an opinionated code formatter. Based on customizable rules it parses your project files and enforces a consistent code style.
In this blog post I am going to describe how to run Prettier with ESLint.
Project setup
To show the general workflow I am going to use a bare minimum JavaScript project with zero configuration. At the beginning the project consists of two files:
index.js
package.json
The index.js
contains a string variable:
var foo = 'bar';
package.json
does not contain any configuration:
{}
Combine ESLint and Prettier
First of all we are going to install the needed dependencies:
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier --save-dev --save-exact
eslint
and prettier
as the main packages and the rest to enable interoperability between those two.
Create a .eslintrc.json
file in the root directory holding the ESLint configuration:
{
"extends": [
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": [
"error"
]
}
}
This bridges the gap between Prettier and ESLint and makes it possible to run them together.
Add "lint": "eslint . --ext .js"
as a script to the package.json
. This script executes ESLint + Prettier for all .js
files starting in the root directory. The package.json
should look like this (package versions might differ though):
{
"scripts": {
"lint": "eslint . --ext .js"
},
"devDependencies": {
"eslint": "8.29.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-prettier": "4.2.1",
"prettier": "2.8.1"
}
}
When running npm run lint
, the console displays this output:
error Replace `''` with `""` prettier/prettier
Prettier complains that single quotation marks should be replaced with double quotation marks. This means everything is working as expected and Prettier runs via ESLint.
Customize formatting rules
Note that Prettier is using its default configuration and no custom rules are defined yet. Let’s say that we actually do want to use single quotation marks. In this case, create the following .prettierrc.json
in the root directory:
{
"singleQuote": true
}
If we run npm run lint
again, the errors are gone.
That’s it. Prettier gets executed via ESLint based on dedicated configuration files.