Preventing Bad Commits With Pre-Commit Hooks and Linters
Let’s walk through how to set up husky and lint-staged to run our linters before writing commits.
Before we begin
I should mention these resources have excellent documentation on how to do everything we will do here, I’ve simply complied them together for our convenience.
Official Docs for Husky, Lint-Staged, ESLint and Prettier
Initialize Git, Node.js and Install devDependencies
From within the terminal we will initialize a new project with version control and Node.js.
$ git init && npm init -y
$ npm i husky lint-staged eslint prettier -D
Configure ESLint
Next we can create an ESLint configuration file. Go ahead and add a new file titled.eslintrc.js
in the same folder as your package.json
If you haven’t already, create a .js
file and let’s add some code with the intention of breaking our linter.
Awesome, now we are ready for the pre-commit hook.
Add Husky and lint-staged pre-commit hook
We will reference lint-staged
from our pre-commit hook using husky.
That’s it! Now we can add and commit our changes. Our pre-commit hook should catch our lint errors and prevent a successful commit. A very useful utility to add to the tool box!
If you’ve found this article useful, I’d love to hear about it! 👋