Complete Set-up Guide for Prettier (with ESLint)

E.Y.
2 min readJul 16, 2020

--

Photo by Anna Kolosyuk on Unsplash

This is a follow-up blog on my previous blog on ESLint. Please have a read as this one will also talk about how to integrate Prettier with ESLint.

So what is Prettier?

Prettier is an opinionated code formatter. The aim of Prettier is to put an end to arguments about code style. It enforces a consistent style by converting your code to a syntax tree and rewriting it with its own rules (that you defined). But it just change the structural view not the functionality of your code.

Installation

You can install Prettier globally or locally.

npm install -g prettiernpm install --save-dev prettier

To configure with ESLint, also install the following dependencies. Note that Prettier replaces ESLint’s formatting rules.

npm install --save-dev eslint-config-prettier eslint-plugin-prettier

While the eslint-config-prettier disable ESLint rules that are in conflict with Prettier, the eslint-plugin-prettier add Prettier rules into ESLint. (There’s really good explanation here)

Lastly add the Prettier configs in your .eslintrc file

{
"extends": ["prettier"],
"plugins": ["prettier"],
"rules": {
"prettier/prettier": ["error"]
},
}

Configure rules

To configure your prettier rules, create a .prettierrc file in your project’s root directory.

I created an example file with some popular rules below:

{
"semi": true",
"trailingComma": "all",
"singleQuote": true,
"printWidth": 70,
"arrowParens": "always",
"tabWidth": 2
}
  • semi: true if you want to print semicolons at the end of every statement, false otherwise.
  • trailingComma": "all" will preserve the trailing commas.
  • singleQuote: true will use single quotes.
  • printWidth: specifies the line length that the printer will wrap on.
  • arrowParens: always use parenthesis around arrow functions
  • tabWidth: use 2 spaces per indentation-level.

Run & Fix

Normally you can integrate prettier into your IDE. For example on VS code, go to inspect editor.formatOnSave setting. You can turn on format-on-save on a per-language basis by scoping the setting:

// Set the default
"editor.formatOnSave": false,
// Enable per-language
"[javascript]": {
"editor.formatOnSave": true
}

Or you can use Prettier CLI, similar to --fix option of ESLint you can use --write . For example the following command will make check .js or .jsx file under src :

prettier --write src/*.(js|jsx)

Then you can use this CLI option to include a format script in your package.json file:

{
"scripts": {
"format": "prettier --write \"**/*.+(js|jsx|json|css|md)\""
}
}

To ignore some files from Prettier, add.prettierignore:

package-lock.json
node_modules/

That’s it! Pretty simple and powerful!

Happy reading!

🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥⭐️ 🌟🐣 🐥

--

--

No responses yet