Published on

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

Authors
  • avatar
    Name
    Hieu Cao
    Twitter

Introduction

Maintaining code quality is essential in software development, especially in collaborative environments. Tools like Husky and Lint-Staged can help enforce best practices by automating tasks during the commit process. By integrating these tools, you can prevent bad code from entering your repository and ensure consistent standards across your project.

In this blog, we'll explore the basics of Husky and Lint-Staged, how they work together, and how to set them up in your projects.

What Is Husky?

Husky is a tool for managing Git hooks. Git hooks are scripts that run at specific points in the Git lifecycle, such as before committing or pushing changes. With Husky, you can:

  • Automate tasks like running linters or tests before committing code.
  • Enforce team-wide standards with minimal effort.

What Is Lint-Staged?

Lint-Staged is a companion tool for running linters (or other scripts) on staged files. It ensures only the files you are about to commit are processed, making pre-commit tasks faster and more efficient.

Benefits of Using Husky and Lint-Staged

  1. Consistency: Automatically enforce code style and quality across the team.
  2. Efficiency: Only process staged files, reducing execution time.
  3. Automation: Eliminate the need for manual checks before committing.

Setting Up Husky and Lint-Staged

Follow these steps to integrate Husky and Lint-Staged into your project.

Step 1: Install Dependencies

Ensure your project is using npm or yarn, then install the necessary packages:

npm install --save-dev husky lint-staged

Step 2: Configure Husky

Husky requires a configuration file to define hooks. Add the following script to your package.json:

{
  "scripts": {
    "prepare": "husky install"
  }
}

Run the prepare script to initialize Husky:

npm run prepare

Add a pre-commit hook:

npx mrm lint-staged

Step 3: Configure Lint-Staged

Add a lint-staged configuration to your package.json or create a .lintstagedrc file:

Example in package.json:

{
  "lint-staged": {
    "*.+(js|jsx|ts|tsx)": [
      "eslint --fix"
    ],
    "*.+(js|jsx|ts|tsx|json|css|md|mdx)": [
      "prettier --write"
    ]
  }
}

Step 4: Test the Setup

  1. Stage some changes:

    git add .
    
  2. Commit the changes:

    git commit -m "Test Husky and Lint-Staged"
    

If configured correctly, Husky will run the pre-commit hook, triggering Lint-Staged to process your files.

Conclusion

Husky and Lint-Staged are powerful tools for automating pre-commit checks and maintaining code quality. By integrating these tools into your workflow, you can save time, improve consistency, and enforce best practices across your team.

Start using Husky and Lint-Staged today to streamline your development process and keep your codebase clean!

Happy coding!