How to Lint Only Staged Files in Angular or React

How to Lint Only Staged Files in Angular or React

Linting is an essential part of modern web development, ensuring that code is consistent, error-free, and adheres to best practices. However, running linters on an entire codebase can be time-consuming, especially in large projects. To optimize this, you can configure your project to lint only the files that are staged for a commit. This guide will show you how to set up linting for staged files in both Angular and React projects using lint-staged and husky.

Why Lint Only Staged Files?

Linting only staged files offers several benefits:

  • Efficiency: Linting only the files that have been modified and are ready to be committed saves time and computational resources.

  • Faster Commits: Developers can commit their changes faster without waiting for the entire codebase to be linted.

  • Focus: It ensures that only the relevant changes are linted, making it easier to catch and fix issues.

Setting Up Linting for Staged Files

To lint only staged files, we'll use two npm packages: husky and lint-staged.

Step 1: Install Dependencies

First, install husky and lint-staged as development dependencies in your project:

Step 2: Configure Husky

Husky is a tool that allows you to easily manage Git hooks. We'll configure it to run lint-staged before every commit.

Add the following configuration to your package.json:

This setup tells Husky to run lint-staged before any commit is made.

Step 3: Configure Lint-Staged

lint-staged runs specified linters on staged files. Configure it in your package.json:

Step 6: Commit and Test

Now, when you stage changes and make a commit, lint-staged will automatically run ESLint (or Angular lint) on the staged files. For example:

Here's a variable that violates the camelCase naming convention in React:

I staged the file as bellow to start commiting it:

And here's the result of commiting the violated change:

And that's the result after commiting the fixed code:

During the commit, Husky will trigger lint-staged, which will then lint and warn you about the errors in the staged files and lint the auto-fixable ones.

Conclusion

By configuring your Angular or React project to lint only staged files, you can significantly improve your development workflow. This setup ensures that your code quality remains high while keeping the linting process efficient and focused. With husky and lint-staged, integrating this workflow into your project is straightforward and highly beneficial. Happy coding!