Linting & Formatting
Linting and formatting are essential practices for maintaining code consistency, readability, and quality. This document provides guidelines for setting up and using linting and formatting tools in a modern frontend project.
Why Linting & Formatting Matter
- Code Consistency: Ensures all team members follow the same coding style.
- Error Prevention: Identifies potential issues before they become bugs.
- Improved Readability: Enhances the clarity of code for current and future developers.
- Automation: Saves time by automating code formatting and error detection.
Linting with ESLint
Installation
Install ESLint as a development dependency:
Configuration
-
Initialize ESLint in your project:
-
Choose the options that suit your project (e.g., TypeScript, React).
-
Example
.eslintrc.json
file:{ "env": { "browser": true, "es2021": true }, "extends": [ "eslint:recommended", "plugin:react/recommended", "plugin:@typescript-eslint/recommended" ], "parser": "@typescript-eslint/parser", "parserOptions": { "ecmaVersion": 12, "sourceType": "module" }, "plugins": ["react", "@typescript-eslint"], "rules": { "indent": ["error", 2], "quotes": ["error", "single"], "semi": ["error", "always"] } }
Running ESLint
-
Check for linting errors:
-
Automatically fix fixable issues:
Formatting with Prettier
Installation
Install Prettier as a development dependency:
Configuration
-
Create a
.prettierrc
file: -
Create a
.prettierignore
file to exclude certain files or directories:
Running Prettier
-
Format files manually:
Integrating ESLint and Prettier
Why Integrate?
Integrating ESLint and Prettier prevents conflicts between linting and formatting rules.
Installation
Install the necessary dependencies:
Configuration
Update your .eslintrc.json
to include Prettier:
{
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:@typescript-eslint/recommended",
"plugin:prettier/recommended"
]
}
Format and Lint Together
Add the following scripts to your package.json
:
IDE Integration
VS Code Setup
-
Install the following extensions:
- ESLint
- Prettier
-
Update your settings in
settings.json
:
CI/CD Integration
Running Linting & Formatting in CI/CD
-
Add a linting step to your CI/CD pipeline:
Key Takeaways
- Use ESLint to enforce coding standards and identify issues.
- Use Prettier for consistent code formatting.
- Integrate ESLint and Prettier to avoid rule conflicts.
- Configure your IDE and CI/CD pipeline for automated linting and formatting.