Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
127 lines (101 sloc) 2.44 KB
layout author title date desc bigimg img categories tags interesting toc todo package-versions redirect_from
post
Wouter Van Schandevijl
Git Hooks with Husky
2019-04-13
Lint, test and try a production build before pushing changes with git hooks and Husky.
url desc origin
git-hooks-husky-big.png
Photo by Chris Scott
url origin desc
git-hooks-husky.jpg
Photo by Simon Rae
dev-setup
git
url desc
Official githooks documentation
title icon
Git Hooks
icon-git
desc url
Use lerna to do the monorepo handling?
husky
1.3.1
/blog/productivity/git-hooks-with-husky/

Avoid pushing changes that break the build with githooks and Husky.

{% include github-stars.html url="typicode/husky" desc="🐺 Git hooks made easy" %}

Hooks

git hooks
Run a program before certain points in git's execution.

They are defined in .git\hooks.
You can find some example files in that directory. Remove their .sample suffix to test them out.

Husky

Hooks are saved locally and not pushed to the remote. Husky allows you to easily make the git hooks part of the repository itself.

npm install husky --save-dev

Add to package.json

{
  "husky": {
    "hooks": {
      "pre-push": "bash prepush.sh",
      "pre-commit": "npm run lint"
    }
  }
}

It's also possible to put the json (without the husky node) in a .huskyrc or .huskyrc.json file.

prepush.sh

Prepush script that works around the frontend project package.json not being in the root of the git repository.

#!/bin/sh

# Path Juggling
originalPath=`pwd`
if [ "`git rev-parse --show-cdup`" != "" ]; then cd `git rev-parse --show-cdup`; fi
cd ./frontend-project-folder/

# Linting
npm run lint
if [ $? -ne 0 ]; then
    cd $originalPath
    exit -1
fi

# Testing
npm test
if [ $? -ne 0 ]; then
  cd $originalPath
  exit -1
fi

# Build
npm run build
hasBuildErrors=$?

cd $originalPath
exit $hasBuildErrors

Other

More control with .huskyrc.js and environment variables.

const tasks = arr => arr.join(' && ');

module.exports = {
  'hooks': {
    'pre-commit': tasks([
      'echo $HUSKY_GIT_PARAMS',
      'echo $HUSKY_GIT_STDIN',
      'echo $HUSKY_DEBUG',
      'echo $HUSKY_SKIP_INSTALL'
    ])
  }
};
You can’t perform that action at this time.