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:
- You try to make a commit
- Husky catches this
- Husky runs whatever commands you’ve set up
- If the commands succeed, the commit happens
- 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 errorsstaged
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
:
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:
{
"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