- Building Enterprise JavaScript Applications
- Daniel Li
- 331字
- 2021-07-23 16:31:15
Adding pre-commit hooks
However, we're not quite finished yet. Many developers are careless and forgetful. Even with eslint installed and the extension configured, they may still forget to run the lint command before committing badly styled code. To help them, we can implement Git hooks, which are programs that are triggerred to run at defined points in Git's execution.
By default, Git hooks are stored inside the .git/hooks directory. If you look inside the directory, you'll find many sample hooks with the .sample file extension. The one we are interested in is the pre-commit hook, which is executed after the git commit command is issued, but before the actual commit is made.
Hooks are written as a shell script. For the pre-commit hook, we can abort the commit by returning a non-zero exit code. Conveniently, when ESLint detects code style violations, it will exit with a status code of 1; therefore, in our script, we can simply return the exit code returned by eslint. When writing a hook manually, you should take care to only use syntax that abides by the POSIX standard, because other developers may use a different type of shell from you.
However, if writing shell scripts manually sounds like too much work for you, there's a tool called Husky, which hugely simplifies the process for us. Let's install it:
$ yarn add husky --dev
Husky will insert its own Git hooks into our project. In these hooks, it will check our package.json for scripts with special names and run them. For instance, our pre-commit hook will check for a script named precommit. Therefore, to run our lint command with Husky, all we have to do is add a new npm script called precommit:
"scripts": {
...
"precommit": "yarn run lint",
...
Now, if we try to commit any badly formatted code, it will throw an error and abort:
...
error Command failed with exit code 1.
husky > pre-commit hook failed (add --no-verify to bypass)