Setting up pre-commit hooks on GitHub is a powerful way to automate tasks and maintain code quality. Pre-commit hooks are scripts that run automatically every time you commit changes. This mechanism helps you catch issues early, reinforcing good coding practices and saving time in the long run.

In this guide, we'll outline a step-by-step process to set up a pre-commit hook using husky, a popular choice for Git hooks, and lint-staged, a pipeline to run linters on git tracked files. This duo will ensure your commits are clean and your codebase maintains a consistent style.

Setting up husky and lint-staged
Both husky and lint-staged are npm packages, so we'll start by installing them globally via npm or yarn. It's as simple as running:

npm install husky lint-staged --save-dev or yarn add husky lint-staged --dev
Installing husky

Husky installs Git hooks directly into your npm scripts. First, install husky as a dev dependency, then enable Git hooks using the following command:
npx husky install
This command will install husky in your project root and enable Git hooks by default.

Configuring lint-staged
Next, configure lint-staged in your package.json. Open your package.json file and add the following configuration:
"lint-staged": { "**.{js,jsx}": [ "eslint", "git add" ] }}

This configuration tells lint-staged to run ESLint on all JavaScript and JSX files before they can be committed. The "git add" command is necessary to stage the files after linting.
Setting up pre-commit hooks




















Now that we have the foundations in place, let's set up the pre-commit hook. Husky will handle the pre-commit hook based on our configured lint-staged script.
No additional configuration is needed for husky to run lint-staged as a pre-commit hook. When you commit changes, husky will automatically run the lint-staged script on staged files.
Testing the pre-commit hook
To test that everything is working as expected, introduce a linting error into one of your JavaScript files. Then, try staging and committing the file. If the pre-commit hook is set up correctly, you should see linting errors printed in the console, and the commit should be aborted.
Once you've fixed the linting error, you should be able to commit your changes without any issues.
And that's it! You've successfully set up pre-commit hooks to ensure your code adheres to best practices before every commit. Happy coding!