DEV Community

loading...

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

azu profile image azu ใƒป2 min read

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 .githook
  • 2. Create .githook/pre-commit and put the following content.

.githook/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 .githook"
  },
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.

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.

Discussion (0)

pic
Editor guide