Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
1 min readDev Tool

Set up Husky 9 in two lines

Install Husky 9, initialize a pre-commit test hook, and check that Git runs it in the next checkout.

Your repo has an npm test command, and you keep remembering to run it after you commit. Put that command in a pre-commit hook so a failed test stops the commit while your changes are still staged.

Install Husky and initialize the hook

Run these lines from the directory with both package.json and the Git checkout. The project should already have a working test script.

npm install --save-dev husky@9
npx husky init

Husky init creates .husky/pre-commit and sets scripts.prepare to husky. In an npm project, the generated hook starts with npm test.

npm test

That is the complete contents of .husky/pre-commit for this example. When you commit, Husky runs the script. A failed test gives Git a nonzero exit status, so Git leaves your change staged and skips creating the commit.

If package.json already had a prepare script, open the diff before committing. The initializer sets that value, so restore any build step your project still needs and combine it with the husky command.

Check what the next checkout needs

Commit .husky/pre-commit, package.json, and package-lock.json with the setup. The generated files under .husky/_ are installed locally. Run npm ci in a fresh checkout with dev dependencies and lifecycle scripts enabled. The checked-in prepare script installs the Git hook files there.

If a commit goes through without running your tests, run git config --get core.hooksPath. In this setup it prints .husky/_. If it is missing, check that you installed dev dependencies and allowed npm to run lifecycle scripts. With dependencies present, run npm run prepare and check the path again.

Keep the hook small enough to use

Try a failing test and a passing test in a scratch commit before asking the rest of the team to install it. If the full suite takes too long for a single commit, change the contents of .husky/pre-commit to call a smaller project script. Run the full suite in CI so changes get the same check when they reach the shared repository.