Published on

Prettier + ESLint + lint-staged + Husky Setup Guide - Part 1

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

Consistency is key in software development. ESLint and Prettier are two popular tools that help maintain code quality and enforce coding standards. By integrating them into your project, you can catch errors early and ensure a consistent code style across your team.

In this blog, we'll explore how to set up and use ESLint and Prettier effectively.

What Is ESLint?

ESLint is a static code analysis tool for identifying problematic patterns in JavaScript code. It can:

  • Detect syntax errors.
  • Enforce coding standards.
  • Highlight potential bugs.

What Is Prettier?

Prettier is a code formatter that enforces a consistent style by parsing and reformatting your code. It focuses on:

  • Wrapping code to fit a defined print width.
  • Consistent indentation and spacing.
  • Automatic handling of trailing commas and semi-colons.

Setting Up ESLint and Prettier

Follow these steps to configure ESLint and Prettier in your project.

Step 1: Install Dependencies

Run the following commands to install ESLint, Prettier, and related plugins:

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

Step 2: Configure ESLint

Create an .eslintrc.json file in your project root:

{
  "env": {
    "browser": true,
    "es2021": true
  },
  "extends": ["eslint:recommended", "plugin:prettier/recommended"],
  "parserOptions": {
    "ecmaVersion": 12,
    "sourceType": "module"
  },
  "rules": {
    "prettier/prettier": "error"
  }
}

Step 3: Configure Prettier

Create a .prettierrc file in your project root:

{
  "semi": true,
  "singleQuote": true,
  "printWidth": 80,
  "tabWidth": 2
}

Step 4: Add Scripts to package.json

Add the following scripts for linting and formatting:

{
  "scripts": {
    "lint": "eslint \"**/*.{js,jsx}\"",
    "format": "prettier --write ."
  }
}

Step 5: Run Linting and Formatting

  • To check for linting errors, run:

    npm run lint
    
  • To format code, run:

    npm run format
    

Tips for Using ESLint and Prettier

  1. Editor Integration: Use extensions for VS Code or your editor to highlight issues in real-time.
  2. Pre-commit Hooks: Combine with tools like Husky and Lint-Staged to enforce checks before commits.

Conclusion

ESLint and Prettier are indispensable tools for ensuring code quality and consistency in modern JavaScript development. By integrating them into your workflow, you can reduce bugs, improve readability, and maintain high standards across your team.