Embracing a robust pre-commit hook workflow in your GitHub repository can significantly enhance your code quality and maintainability. It allows you to automate tasks, run tests, and ensure code quality before any commit is pushed. Here, we'll explore a comprehensive example of GitHub pre-commit hooks using Husky and lint-staged.

Before delving into the example, let's understand the basic concept. Pre-commit hooks are scripts that Git runs automatically when a user tries to commit changes. They provide a way to automate testing, linting, and more, right when it's needed most - before a commit is finalized.
![Create a Free Blog with Jekyll and GitHub Pages - [Step-by-Step Guide]](https://i.pinimg.com/originals/8e/39/7b/8e397b773157d46602a5c160758a7469.png)
Setting Up the Pre-Commit Hook Environment
Our example uses Husky for managing Git hooks and lint-staged for running linters and fixers on Git staged files. First, install them as dev dependencies:

`npm install husky --save-dev`
`npm install lint-staged --save-dev`

Initializing Husky
After installation, initialize Husky in your repository:
`npx husky install`

This will set up a .husky directory in your root with pre-commit and prepare-commit-msg hooks.
Configuring lint-staged
Next, configure lint-staged in your package.json:

```json "lint-staged": { "*.{js,jsx,ts,tsx}": ["eslint --fix", "git add"] } ```
The above configuration runs ESLint on all JavaScript/TypeScript files before committing, applying fixes and adding the staged files to the commit.
Creating a Custom Pre-Commit Hook







![[2/7 Balance Patch] Charlotte Rework + Buffs for Various Characters | Epic Seven Wiki for Beginners](https://i.pinimg.com/originals/24/40/43/244043919cc4d10ac182063ff3858977.png)












Sometimes, you might need a custom pre-commit hook. Let's create one that says a friendly greeting before every commit:
Setting Up the Custom Hook Script
Create a .huskyrc.js file in your root directory with the following content:
```javascript module.exports = { hooks: { 'pre-commit': 'echo "Hello, committer! 👋"' } }; ```
Now, every time you try to commit changes, you'll see a friendly greeting.
Running Tests Before Commit
Let's extend our example to run tests before committing:
Update the pre-commit hook in .huskyrc.js:
```javascript module.exports = { hooks: { 'pre-commit': 'echo "Hello, committer! 👋" && npm run test' } }; ```
This will run your tests (assuming you have a test script in your package.json) every time you try to commit, ensuring your changes haven't broken any tests.
In conclusion, leveraging pre-commit hooks in your GitHub workflow can boost your productivity and code quality. The example above demonstrates how to set up a robust pre-commit hook environment using Husky and lint-staged, and how to create a custom pre-commit hook for running tests. Start customizing your Git pre-commit hooks today to automate your workflow and ensure code quality!