So I went into a rabbit hole of setting up Husky’s git hooks with Lerna and realized that there wasn’t a straightforward guide to setting up the latest version of Husky with Lerna. So here goes.
The following setup steps are yarn specific. You can replace yarn with npm for step 1 and replace yarn with npx for all the other steps.
yarn add --dev -W husky
Install Husky as a dev dependency on your project root
yarn husky install
Git hooks are actually a Git feature and not a Husky feature (something I did not know). So when you run the above command, Husky will change the git hooks directory from .git/hooks
in your project root (where you will find samples from git about what you can do with hooks) to .husky/
. You can read more about what git hooks are available here.
You can verify that this install was successful by checking if the hook’s path was successfully changed
git config core.hooksPath
Should return .husky
You can customize a git hook in Husky using the following command:
yarn husky add .husky/pre-commit "yarn test"
You can now see that a new file has been created .husky/pre-commit
. To quickly verify that this is indeed working, you can edit the file to print something and exit.
echo "Hello World"
exit 1
Now add and commit the files that were created in your .husky directory to test the pre-commit hooks.
git add .husky/pre-commit
git commit -m "Test commit"
This should print “Hello World” and then not commit the files (because we returned exit code 1 from the pre-commit hook).
You can set up the root pre-commit and pre-push hooks in such a way that it works well with multiple packages.
From the root of the project, add pre-commit and pre-push hooks:
yarn husky add .husky/pre-commit "yarn lerna run pre-commit"
yarn husky add .husky/pre-push "yarn lerna run pre-push"
This allows you to setup package specific pre-commit
and pre-push
steps by adding to the packages scripts
in the package.json
like this:
// packages/package-1/package.json
{
...
"scripts": {
...
"pre-push": "yarn lint-changed; yarn test-changed",
...
}
...
}
Install commitlint along with lerna specific peer dependencies
yarn add --dev -W @commitlint/cli @commitlint/config-conventional \\
@commitlint/config-lerna-scopes
Add the commit-message
hook to husky
yarn husky add .husky/commit-message "yarn commitlint --edit $1"