Mastodon

Minifying & Optimizing static websites using GitHub actions

Aug 03, 2020 by Kolappan N

If you are using GitHub to host the repository for your static websites, you can use GitHub actions and GitHub marketplace apps to optimize your static automatically. The GitHub actions is a great CI/CD tool and here is how I use it to minify my static sites such as this blog.

My setup

1. Optimising Images

Images are a large part of the website in terms of bandwidth. Optimizing images can go a long way. There are many ways to do this, such as using a modern format that offers more compression or using various images sizes for different devices. However the method I discuss here is much more simple, we just compress all new images that are added to the source code automatically. One of the benefits of this approach is that you can use it along with other approaches such as using modern image formats.

The tool I use for this is ImgBot. It is a simple bot that runs once there is a commit in your repo, losslessly optimize images and submit a pull request. It is free to use for open source projects. You can configure it to run lossy compression if you want it.

A Pull request from ImgBot
A Pull request from ImgBot

2. Minifying HTML, CSS and JavaScript in CI/CD

Compared with the images, I don’t want to keep the minified files of HTML and CSS in the source control. I need the full version of the files for development. So, here I use GitHub actions to minify the files during deployment.

You can compress CSS in Jekyll using a simple config variable and it is also possible to minify HTML using a Jekyll layout. I really loved those methods but I also had a few single page website that don’t use Jekyll such as my Resume. I found the below method to be useful for all my projects.

There is a CLI open source implementation called minify that can be easily used in and command line CI/CD tool to minify files on the go. It minifies all the HTML, CSS, JS, JSON, SVG and XML. That is the feature I like most.

Here is my implementation of it.

- name: Installing minifier
  run: sudo apt-get install minify
- name: Minifying files
  run: minify -r ./site-dist/ -o ./site-dist/ --html-keep-document-tags --html-keep-end-tags --html-keep-default-attrval

There is no universal method to this. This is how I do it. If you use a better CLI tool or have a better GitHub app or action, leave it in the comment below.