This guide will help configure ESLint (for code quality) and Prettier (for code formatting) in a React project to ensure consistency across the team.
1. Install ESLint and Prettier
Install the necessary dependencies:
npm install eslint prettier eslint-config-prettier eslint-plugin-prettier --save-dev
-
eslint-config-prettier
: Disables ESLint rules that conflict with Prettier. -
eslint-plugin-prettier
: Runs Prettier as an ESLint rule to flag formatting issues.
2. Configure ESLint
Create or update the .eslintrc.json
file in the root of the project:
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:prettier/recommended"
],
"parserOptions": {
"ecmaVersion": 2021,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"rules": {
// Optional: Add extra linting rules if required
}
}
-
plugin:prettier/recommended
: Ensures Prettier rules are enforced and disables conflicting ESLint rules.
3. Create Prettier Configuration
Customize Prettier's behavior by placing .prettierrc
file in the project root:
{
"singleQuote": true,
"semi": true,
"trailingComma": "es5"
}
Note : This can be optional if we want to honor Prettier's default settings but we will keep it for finer control.
4. Configure VSCode for Consistency
Create a .vscode/settings.json
file to enforce formatting and linting in VSCode:
{
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": true
},
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
]
}
-
editor.formatOnSave
: Automatically formats code using Prettier on save. -
source.fixAll.eslint
: Automatically fixes ESLint issues on save.
5. Push .vscode
to the Repository
Ensure that the .vscode
folder is added to version control so everyone has the same settings. Add this to .gitignore
:
.vscode/*
!.vscode/settings.json
6. Set Up Husky for Pre-Commit Hooks [If you are not using VSCode]
To enforce linting and formatting before code is committed, use Husky and lint-staged, this is specially useful if you are not using VSCode as your IDE:
npx husky-init && npm install
npm install lint-staged --save-dev
Add the following to your package.json
:
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{js,jsx,ts,tsx}": ["eslint --fix", "prettier --write"]
}
}
7. Running ESLint and Prettier (Optional manual step)
-
Lint your code:
npx eslint .
-
Format your code:
npx prettier --write .
Note : Setting up
.vscode/settings.json
orhusky
eliminates the need to do this manual step.
Result
- VSCode: Automatically applies consistent formatting and linting across all machines with shared settings.
- ESLint & Prettier: Enforce code correctness (ESLint) and consistent formatting (Prettier).
- Pre-commit hooks (if not using VSCode): Ensure no code is committed without passing lint and format checks.