DEV Community

Discussion on: How to add TailwindCSS to your Hugo site

 
divrhino profile image
Div Rhino • Edited

Hello Kareem,

Although you've directed your comment above to Sarah, I thought I'd interject with some tips that may be helpful. Firstly, optimising CSS in this instance probably has more to do with TailwindCSS than with Hugo. So here are just a few things that have helped me:

  1. TailwindCSS allows you to use PurgeCSS to remove styles that aren't being used. Writing purgeable HTML helps the purge process. You can configure PurgeCSS in your tailwind.config.
  2. I often find that I tend to use a custom colour palette in most of the sites I design and build, so I avoid extending the Tailwind colours and just use custom colours in my config, instead
  3. Because flexbox and CSS grid are now pretty well-supported, I don't often find a need for certain things like floats. So being able to remove floats and similar features is very handy.

The tailwind docs have more useful optimisations.

Hope this is a useful starting point. :) 🍍

Thread Thread
 
littleninja profile image
Sarah (she/her)

This is a useful starting point! To add, the official Hugo docs show how to purge CSS with PostProcess. I was able to optimize my Tailwind styles without modifying the Tailwind config, but Div Rhino's suggestions can help you optimize further.

Here are the steps in code. These details are also in the link above to the Hugo docs:

First, in your config file:

[build]
  writeStats = true
Enter fullscreen mode Exit fullscreen mode

Next, in your PostCSS config file:

const purgecss = require('@fullhuman/postcss-purgecss')({
    content: [ './hugo_stats.json' ],
    defaultExtractor: (content) => {
        let els = JSON.parse(content).htmlElements;
        return els.tags.concat(els.classes, els.ids);
    }
});

module.exports = {
    plugins: [
        require('tailwindcss'),
        require('autoprefixer'),
        ...(process.env.HUGO_ENVIRONMENT === 'production' ? [ purgecss ] : [])
    ]
};
Enter fullscreen mode Exit fullscreen mode

Lastly, in your layout file (layouts/_default/baseOf.html or a style partial):

{{ $css := resources.Get "css/main.css" }}
{{ $css = $css | resources.PostCSS }}
{{ if hugo.IsProduction }}
{{ $css = $css | minify | fingerprint | resources.PostProcess }}
{{ end }}
<link href="{{ $css.RelPermalink }}" rel="stylesheet" />
Enter fullscreen mode Exit fullscreen mode

To walk through what's happening here:

  1. Add configuration writeStats = true. If successful, this will write a hugo_stats.json file at the root of your theme or site.
  2. Add PurgeCSS with a custom extractor to your PostCSS config. The custom extractor will use the class names extracted by the hugo_stats.json and glob patterns to find your layout files to optimize Tailwind styles.
  3. Add a pipe to apply resources.PostProcess in the layout file where you define your styles.