DEV Community

Discussion on: How to add TailwindCSS to your Hugo site

 
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.