Prettier and ESlint setup in React | NextJs Project.

First thing, what's the use case of Prettier and Eslint ?

Prettier: It's a code formatter, used to beautify your code 💅

Eslint: To find and fix problems in your JS code. 😄

ussop drinking coffee

Prettier 💅

Prettier is used for code formatting, it supports multiple languages. We can setup prettier with our code editors like VS code. The Benefit of using Prettier is that our code will follow specific rules. We can write the rules in the Prettier configuration file.

Eslint 😄

ESLint is a tool for identifying and reporting on patterns found in ECMAScript/JavaScript code, with the goal of making code more consistent and avoiding bugs. Eslint will display red line below the code if a particular code doesn't follow the specified rules. We can write the rules in the ESLint configuration file.

Install Eslint and Prettier's plugin in VSCode

In the Extension marketplace of VSCode

For ESLint, search for the ESLint by microsoft. enter image description here

For Prettier, search Preetier by prettier.io
enter image description here

After installing both Prettier and Eslint, open the settings.json file of vscode. Paste the following json in it

{
	"editor.formatOnSave": true,
	"editor.defaultFormatter": "esbenp.prettier-vscode",
	"[typescript]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	 },
	"[javascript]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	 },
	"[typescriptreact]": {
		"editor.defaultFormatter": "esbenp.prettier-vscode"
	 },
	"prettier.jsxSingleQuote": true,
	"prettier.singleQuote": true
}

this contains the VSCode configuration of Prettier. After this Prettier will format the code with default rules.

setup Eslint and Prettier rules in a NextJS project.

NextJs cause React docs no longer suggests the create-react-app to start a react project.

Install Prettier

	npm install --save-dev --save-exact prettier

Next, create a .prettierignore file to let the Prettier CLI and editors know which files to not format.

# Ignore artifacts: 
build 
coverage

Rules for Prettier:

Create a .prettierrc.json file in your project, this fill will contain the rules for prettier

{ 
   "trailingComma": "es5",
   "tabWidth": 4,
   "semi": false,
   "singleQuote": true
}

Read more about rules and configuration here.

Rules for ESLint:

NextJs by default comes with eslint installed, we can add the eslint rules in the .eslintrc.json file.

{
	"extends": "next/core-web-vitals"
}

Read more about Configurations here.

Prettier setup for NextJS + TailwindCSS

https://tailwindcss.com/blog/automatic-class-sorting-with-prettier
npm install -D prettier prettier-plugin-tailwindcss

extend .prettierrc.json file

   {
     ...
     "plugins": ["prettier-plugin-tailwindcss"],
   }  

Thanks for reading the article 🎉