Update: There is a better way to add pre-commit hooks to your project. Checkout husky. You can follow the below-given tutorial to learn how to manually add pre-commit hooks.
Before we go ahead, I’d like to provide a little background on ESLint and Git pre-commit hook. If you’re familiar with them, you can skip the next two sections.
Developers tend to commit mistakes while coding. For example, you might forget to close a bracket or you might end up creating a variable that already exists. But, mistakes like this might end up breaking your app or site. We might push this buggy code to a cloud repository or it might take considerable amount of time to resolve the issues caused due to such mistakes. If your code is being reviewed, it would consume your reviewers time to find such sloppy mistakes or they might miss it completely.
This is where linting comes in to picture. Linting is the process of running a program that will analyse code for potential errors. For linting such potential errors, we use Linters.
Linters help in making a developer write clean code. Every language might have their own linters to lint their code. Here is a link that I liked which has listed some good linters for writing cleaner code:
Git pre-commit hook
While discussing about ESLint, I gave an example mentioning that a developer might end up pushing a buggy code even if the code is not valid. Even if you have set up a linter, it might guard you against invalid code but it cannot guard you from pushing this invalid code to the repo. We need a mechanism to stop pushing such code to the repo.
This is where Git pre-commit hook. It’ll block the developer from committing the code if it doesn’t pass the rules set by the hooks available in
.git/hooks. These hooks are supposed to be executable.
Please note, that Git pre-commit hook can be used for more than just validating your code. For information about Git Hooks, please visit https://git-scm.com/book/gr/v2/Customizing-Git-Git-Hooks
ESLint Git pre-commit hook
I’d be using an existing script https://gist.github.com/linhmtran168/2286aeafe747e78f53bf
- If you haven’t initialised git for your repo then do so by running the command:
- You should see a
.gitfolder created in your project folder.
- Go to
.git/hooks. You would see a file named
- Rename that file to
- Remove the existing sample code.
- I modified the script https://gist.github.com/linhmtran168/2286aeafe747e78f53bf as per iamjochem’s comment in the Gist and created my own Gist to use it with ESLint.
chmod +x .git/hooks/pre-committo make it an executable file.
I’d love to hear feedback/suggestions for improvement.