../

Using Git Hooks with Yarn 3

With Yarn 2, you could easily install Husky by setting your package to private and defining a `postinstall` script:

{
	"private": true,
	"scripts": {
		"postinstall": "husky install"
	},
	"packageManager": "yarn@2.4.3"
}

However, Yarn 3 doesn't seem to work with postinstall. This means that you can't use Husky with Yarn 3 without some extra work.

plugin-install-husky

Wanna know what awesome feature Yarn 3 has? A plugin system! This means that you can write your own plugins to extend Yarn's functionality.

At Truffle, we've been using this short script to install Husky.

// Creative Commons (c) 2022 Spore, Inc. 
const { exec } = require('child_process');

const plugin = {
	default: {
		hooks: {
			afterAllInstalled: async () =>
				exec('git config core.hooksPath .github/hooks'),
		},
	},
};

module.exports = {
	name: 'plugin-install-husky',
	factory: () => plugin,
};

But, frankly, since we have plugins, we don't really need to use Husky. Introducing...

plugin-git-hooks

Lets eject Husky! Start by running yarn remove husky and delete the postinstall script from package.json.

Now, you can move your scripts from .husky to anywhere else. I recommend .github/hooks.

Then, import the plugin.

yarn plugin import https://raw.githubusercontent.com/trufflehq/yarn-plugin-git-hooks/main/bundles/%40yarnpkg/plugin-git-hooks.js

Finally, add the path to your hooks in .yarnrc.yml:

gitHooksPath: .github/hooks

Now, whenever you run yarn (once packages are installed), your hooks will be configured.

Thanks to Truffle for letting me open-source this plugin!