Git Hooks without extra dependencies like Husky in Node.js project

azu

azu

Posted on February 22, 2021

Git Hooks without extra dependencies like Husky in Node.js project

Git 2.9+ supports core.hooksPath for local git hooks, so we do not need extra dependencies like husky.

lint-staged recommented to use with husky.
However, husky v5.0.0 is licesed under The Parity Public License.

We can use core.hooksPath instead of husky.

馃摑 husky v5 also use core.hooksPath internally. It is a wrapper for some commands and provide extra features.

Setup

Setup for lint-staged.

  • 1. mkdir .githooks
  • 2. Create .githooks/pre-commit and put the following content.

.githooks/pre-commmit:

#!/bin/sh
npx --no-install lint-staged
Enter fullscreen mode Exit fullscreen mode
  • 3. Add prepare lifecycle script to package.json
  "scripts": {
    "prepare": "git config --local core.hooksPath .githooks"
  },
Enter fullscreen mode Exit fullscreen mode

Complete to setup! 馃帀

This prepare hooks is exected when the user has run npm install or yarn install.

馃摑 You can also use postinstall hook.
However, If your package is not private and you're publishing it on a registry like npmjs.com, you should not use postinstall scripts.

See also Husky's documentation.

Pros

  • no dependencies

Cons

  • not available add command like husky add
  • can not run local hooks and global hooks at once(husky <=v4 and simple-git-hooks allow it because these does not use core.hooksPath)

Example

It is an example repository.

Note

Some environment like Cloudflare Pages or Heroku clone the repository without .git directory for deploying the repository.

In the env, you will see the following errors

fatal: Not a git repository
Enter fullscreen mode Exit fullscreen mode

You can avoid this error by following changes.

  "scripts": {
-    "prepare": "git config --local core.hooksPath .githook"
+    "prepare": "git config --local core.hooksPath .githook || echo 'Can not set git hooks'"
  },
Enter fullscreen mode Exit fullscreen mode

See also Disable hooks in CI - Husky.

馃挅 馃挭 馃檯 馃毄
azu
azu

Posted on February 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related