How to Auto Compress Your CSS and JS with Git Hooks
1. Download Components
For this tutorial, I will be using Node.JS components - so you will need Node.JS installed. The two packages you will need will be
npm install terser -g npm install cssnano -g
-g here because we want to run these from the command line. Next, you need to find your git hooks directory. If you want to create your own custom git hooks, directory, please follow this tutorial.
Otherwise, you can find your git hooks directory in
.git/hooks within your repository. You will want to edit this file in every location where you do a git merge. This might mean on a local computer, or on your production server.
If you follow the tutorial mentioned before you can do it without having to edit it in multiple places, though. 😉
2. Create your hook
Next, create a file called
post-merge in your hooks directory. Put the following in that file:
echo 'Installing Modules..' npm install echo 'Compressing CSS..' cssnano views/style.css views/style.css cssnano views/async.css views/async.css echo 'Compressing JS..' terser views/local.js --output views/local.js --compress --mangle
I have added 3 lines here: 2 for cssnano, and 1 for terser. If you want more, you can add extra lines to refer to different files.
The cssnano syntax is
cssnano link/to/old/file.css link/to/new/file.css, so update the two lines referring to cssnano to reference your files instead. I am simply overwriting the files on the server, but this may not be suitable for you.
For terser, the syntax is similar, that being
terser link/to/oldJs.js --output link/to/newJs.js --compress --mangle. There are a few more options with terser, which you can view on their NPM page, but this will cover our needs.
I have also added some information as the files load, so you are aware of what's happening for debugging purposes.
3. Run your merge
Now you've added the
post-merge file, when you run
git pull or
git merge, these commands will run immediately after. That means all your newly loaded CSS and JS files will be compressed, resulting in faster load times for your users.
More Tips and Tricks for Git
- Using Git to see recent changes in specified a time period
- How to make Git forget a tracked file now in .gitignore
- Resolving Git Merge Conflicts
- Git Stash - Everything about stashing changes in git
- How to amend and update a git commit
- Setting upstream with Git
- A Step by Step Guide to Git Branches
- The Complete Beginners Guide to Getting Started with Git
- Git blame - How to find out who modified a line with Git
- How to undo a git pull