Preventing Bad Commits With Pre-Commit Hooks and Linters

Matthew Bub
2 min readJan 17, 2021

--

Let’s walk through how to set up husky and lint-staged to run our linters before writing commits.

stop sign to suggest how we will prevent a bad commit

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

Basic ESLint configuration file

If you haven’t already, create a .js file and let’s add some code with the intention of breaking our linter.

This code will break the linter based on our rules.

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.

Pre-commit hook example in our package.json

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! 👋

--

--

Matthew Bub
Matthew Bub

Written by Matthew Bub

A friend, software engineer and writer

Responses (1)