I was looking at the Google PageSpeed1 report for my website as that’s just the kind of thing I get up to on a Sunday, when I noticed that none of my CSS was minified, and it was adding up to a second to page loads.
“This will be easy I thought, surely there’s a simple way to do this out-of-the-box with Hugo”. Well, there is a way, but it’s not that simple.
Getting set up
First, you need to make sure your CSS assets are in a directory called
static as some older themes will have them.
You can just rename
assets and be done with it.
Modifying the head partial
This is where you tell Hugo that you want something to be minified.
Here’s how I do it in my
- Line one gets the resource from your
assetsfolder (remember not
static) and assigns it to a variable called
- Line two takes that
$cssvariable, pipes into a minification function, and then finally adds a cache-buster.
- Line four is the
<link rel>for loading the correctly minified and fingerprinted CSS file.
Now your CSS is minified, and since we’ve added a cache-buster fingerprint we can make changes to it without having to wait for Cloudfront to invalidate their cache (more on this in a further blog post).