Task Automation with Pre-Commit Hooks

Instead of manually linting and formatting our code, we can do this automatically when we try to commit it.

What is Husky?

Husky is a tool that helps you run commands before Git events happen.

It’s named after the dog breed because it acts like a watchdog for your Git actions.

The most common use is running commands before a commit happens - this is called a “pre-commit hook”. Without Husky, Git would just commit your files without any checks.

What are Pre-Commit Hooks?

A pre-commit hook is code that runs right before your code gets committed. With Husky watching:

  1. You try to make a commit
  2. Husky catches this
  3. Husky runs whatever commands you’ve set up
  4. If the commands succeed, the commit happens
  5. If they fail, the commit is stopped

What is lint-staged?

The name “lint-staged” tells us what it does:

  • lint means checking code for errors
  • staged means it only checks files you’re trying to commit

For example:

  • If you change 10 files but only stage 2 for commit
  • lint-staged will only check those 2 files

This makes it fast because it doesn’t check unchanged files.

Setting It Up

The easiest way to set up pre-commit hooks is to usemrm:

bash
	npx mrm lint-staged

This command:

  • Installs husky and lint-staged
  • Sets up the pre-commit hook
  • Creates the basic lint-staged config in your package.json

Using ESLint and Prettier

Add this configuration to your package.json:

json
	{
	  "lint-staged": {
	    "*.js": [
	      "prettier --write",
	      "eslint --fix"
	    ],
	    "*.html": [
	      "prettier --write"
	    ]
	  }
	}

How It Works

  • You stage some files with git add
  • You try to commit with git commit
  • Husky catches this and runs lint-staged

lint-staged:

  • Looks at your staged files
  • Runs the configured tools only on those files
  • Fixes what it can
  • Reports any errors it can’t fix