DEV Community

azu
azu

Posted on • Updated on

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.

Top comments (2)

Collapse
 
azu profile image
azu • Edited

simple-git-hooks is alternative of husky.

My points:

  • Conbination global git hook and local git hook:
  • Dependencies:
    • No dependencies: My Approach
    • Single dependency: simple-git-hooks, husky v5
    • Multiple dependencies: husky v4
Collapse
 
aisone profile image
Aaron Gong

brilliant