Git

How to Auto Compress Your CSS and JS with Git Hooks

Last Updated Saturday, 16 January 2021

When you push your code to production, you ideally want your Javascript and CSS files on the client side to be compressed. Some developers still do this manually, but it is very easy to do automatically if you are using Git.

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 terser and cssnano. These cover javascript and CSS respectively. To install both of these, you can do it as shown:

shell Copy
npm install terser -g npm install cssnano -g

We use -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:

shell Copy
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.