Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

AK DevCraft
AK DevCraftSubscriber

Posted on • Edited on

     

Git pre-hook: Setup pre-commit hook for NPM project example

Introduction

There are various Git pre-hooks that are quite helpful for several essential tasks we want to execute before git commit or push or rebase etc. Basically, there are various use cases, like running linting before you commit the code or running unit tests before commit or push.

Note: Whenever a Git repository is initialized, Git creates sample hooks inside.git/hooks directory under the project directory. E.g..git/hooks/pre-commit.sample. Remember this is hidden directory.

Getting Started

Below are the steps on how to configure pre-commit Git pre-hook for an NPM project.

1. Create a pre-hook script

Let's create apre-commit file inside a newscripts directory. Use case is to execute the unit tests before code commit.

Note: The file name needs to be strictly aspre-commit, because we’re going to Git pre-hook mechanism.

#!/bin/shecho"*****Running unit tests******"stash_commit="$(git stash create)"git reset —-hardnpmtest----watchAll=falsestatus=$?if[[-n"${stash_commit}"]]thengit stash apply"${stash_commit}"fiexit$status
Enter fullscreen modeExit fullscreen mode

Above command stash the working directory changes before running the unit tests, and unstash back. This makes sure, we're running the tests only in the clean working directory. (as this is been configured for pre-commit, changes must have been staged, make sense?😀)

2. Create NPM script

Next up, create an NPM script in thepackage.json file to install thepre-commit script. Why do we need it? because, we want this to run on all developers' machine, not just on our machine, we all love consistency and wants to put the constraint.

"scripts":{"prestart":"cp scripts/pre-commit .git/hooks/ && chmod +x .git/hooks/pre-commit && echo 'hook copied'",...}
Enter fullscreen modeExit fullscreen mode

Here thepre-commit file is created inside project root directory i.e.scripts

The above NPM script first copy the already createdpre-commit file under project’s Git hook directory and set the executable permission, finally just print the message. As we have configured it to run as a part of prestart script, it will run whenever someone starts the application and assuming that developer who is making changes will run thenpm start at least once and I hope I'm right😉.

Once pre-commit script is copied to.git/hooks/ directory, we're all set. We can verify its content as below:

cat .git/hooks/pre-commit
Enter fullscreen modeExit fullscreen mode

Now, next time whenever someone will rungit commit, it will first run thenpm test -- --watchAll=false.

E.g.

ak@--mac git-pre-commit-with-npm % git commit-am"update"-- Output*****Running unit tests******> git-pre-commit-with-npm@0.1.0test /users/ak/git-pre-commit-with-npm> react-scriptstest"--watchAll=false" PASS  src/App.test.js  ✓ renders learn reactlink(29 ms)Test Suites: 1 passed, 1 totalTests:       1 passed, 1 totalSnapshots:   0 totalTime:        0.964 s, estimated 1 sRan alltestsuites.[main 0b432f0] update 1 file changed, 4 insertions(+)
Enter fullscreen modeExit fullscreen mode

Final Notes

  • The waynpm test is configured, in the same way, any other tasks can be executed. And of course for other tasks stash and unstash won't be compulsory.
  • Similarly other pre-hooks can be configured. Here are a few more examples,Pre-hooks Examples.

Sample Code

Here is theGitHub repo with an example.

My other Blogs:

If you have reached here, then I did a satisfactory effort to keep you reading. Please be kind to leave any comments or ask for any corrections.Happy Coding!

Top comments(2)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
artu_hnrq profile image
Arthur Henrique
Enthusiastic learner • Computer scientist • Python developer • Software business analyst • Unix-like system user
  • Location
    Brazil
  • Education
    Computer Science at UFSC, Brazil
  • Pronouns
    He/Him
  • Work
    Enthusiastic learner
  • Joined

Uol. It's actually a lot simple to set git hooks up... I was wondering the other hooks one could configure
Thanks for sharing!

CollapseExpand
 
paul_roberts_ffd5e2df812b profile image
Paul Roberts
  • Joined

If you use the"postinstall" script instead of"prestart", then this will run when anyone doesnpm ci (ornpm install)

Probably easier to just use the pre-commit package which does all this for you

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack Software Engineer, creating digital solutions across various platforms. Programming and software engineering are essential part of my life just like air 😎
  • Work
    Software Engineer
  • Joined

More fromAK DevCraft

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp