How to add PurgeCSS to Hugo

One of the best optimizations you can add to your static site generated with Hugo is purging unused CSS.

Today we'll be using the veteran PurgeCSS with the out of the box PostCSS support from Hugo.

Did you know Tailwind CSS uses PurgeCSS as well?

From 80kb to 10kb

For my Hugo project I reduced this much the size of the CSS output. Which is amazing.

How to do it?

Create a package.json

We'll be using 2 NPM packages:

Here's the minimal setup:

{ "name": "name", "version": "1.0.0", "description": "description", "dependencies": { "@fullhuman/postcss-purgecss": "^4.0.0", "postcss-cli": "^8.3.1" } }
Code language: JSON / JSON with Comments (json)

Create a postcss.config.js

You need to create a configuration file. The content parameter can also include paths to JavaScript files, should you have HTML or CSS classes inside them.

Here's mine:

module.exports = { map: false, plugins: { '@fullhuman/postcss-purgecss': { content: ['./themes/**/*.html'], } } };
Code language: JavaScript (javascript)

Pipe the postCSS rule to the header

Now we just need to pipe this into the head, where you're printing your CSS file (or contents of it).

Mine looks like this:

{{ $main := resources.Get "sass/main.scss" | resources.ToCSS (dict "outputStyle" "compressed") | postCSS}} <link rel="stylesheet" href="{{ $main.RelPermalink }}">
Code language: PHP (php)

The generated file will be compressed and stripped down of the unnecessary selectors.

Handcrafted CSS isn't an issue

Certainly, if you're handcrafting your CSS from scratch you probably don't need this. In my case for professional work we optimize the heck out of everything, meaning using handcrafted CSS with only what's necessary.

Now, for side projects I usually rely on Bootstrap. I know the framework, I'm fast with it so that's what I use. Thus, for those side projects where I drop a big framework I use PurgeCSS.

PD: Yes, I know you can selectively import components in Bootstrap, instead of the whole framework. But even if you just import, say, "forms" you probably will have unused CSS. It's worth exploring PurgeCSS.

About Ricard Torres

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

@ricard_dev @ricard_dev

📝 Blog 🎙 Podcast

Leave a Reply

Add <code> Some Code </code> by using this tags.