When working on a project you usually install various packages from npm.
Of course these packages are maintained and updated, adding more features and security fixes, and stability patches.
One person on your team should run
npm outdated once per week to see what all has been updated and test if you can integrate the packages into your project.
package.json is updated and causes a grand problem for all other developers on the project. If a package has major breaking changes the code will need to be adjusted, however that code will not run on the other develoepers environment. The other developers working on the project they have to run
npm update to install the missing / outdated packages in their environment.
The solution to this problem are “git hooks”, essentially git can execute code on specific events, like before commiting your code, or pre push etc.
git hooks. For my use case I would like to run
npm update after a developer checks out from the git repository, this is the event “post-checkout”.
Native Git Hooks
To create a git hook you need to add a file in your project called
.git/hooks/post-checkout (On linux add the executable bit with
echo "[post-checkout hook: $1]"
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"
echo "$changed_files" | grep -E --quiet "$1" && eval "$2"
check_run package.json "npm update"
exit 0 #Needed so Visual Studio Code does not display an error
You will test this and say, yes this works as intended – lets commit it to the repository. – Now you will discover that you cannot commit files in
.git to the repository.
In fact git does not allow you to do this, due to security concerns as git hooks can execute any shell script.
The work around for this issue is to simply add it into a folder called
git-hooks/ and tell the developers to copy the file when they set up their dev environment.
Husky uses the package.json to define the scripts that are executed via git hooks.
Simply Install Husky
npm install husky -D
Then edit the package.json:
"name" : "test Project"
"postupdate": "npm update"
The Husky solution would also allow you to execute your own js file, maybe also doing some cleanup of files or running tests etc.