Zalgorithm

Using Tailwindcss in a Hugo theme

Source: Hugo docs: TailwindCSS.

Edit: for the way I was using it, styling the blog with Tailwind seemed unnecessary. It’s now just using plain CSS.

Install the Tailwind CSS CLI (v4.0 or later):

npm install --save-dev tailwindcss @tailwindcss/cli

Add the following to the site’s (or possibly the theme’s) configuration file:

# site hugo.toml
[build]
  [build.buildStats]
    enable = true
  [[build.cachebusters]]
    source = 'assets/notwatching/hugo_stats\.json'
    target = 'css'
  [[build.cachebusters]]
    source = '(postcss|tailwind)\.config\.js'
    target = 'css'
[module]
  [[module.mounts]]
    source = 'assets'
    target = 'assets'
  [[module.mounts]]
    disableWatch = true
    source = 'hugo_stats.json'
    target = 'assets/notwatching/hugo_stats.json'

Create a CSS entry file (e.g., assets/css/main.css):

@import "tailwindcss";
@plugin "@tailwindcss/typography"; /* not in the docs, but I'm using it */
@source "hugo_stats.json";

Create a partial template to process the CSS with the Tailwind CSS CLI tool that was installed above:

{{ with resources.Get "css/main.css" }} {{ $opts := dict "minify" (not
hugo.IsDevelopment) }} {{ with . | css.TailwindCSS $opts }} {{ if
hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}" />
{{ else }} {{ with . | fingerprint }}
<link
  rel="stylesheet"
  href="{{ .RelPermalink }}"
  integrity="{{ .Data.Integrity }}"
  crossorigin="anonymous"
/>
{{ end }} {{ end }} {{ end }} {{ end }}

Call the template from the base template (baseof.html):

The Hugo docs do this:

<head>
  ... {{ with (templates.Defer (dict "key" "global")) }} {{ partial "css.html" .
  }} {{ end }} ...
</head>

templates.Defer in the code above defers template execution until (I think) everything has been rendered.

I’m doing this (in _partials/head.html):

{{ partialCached "head/css.html" . }}

Possibly I should change this.

Related to the use of templates.Defer, maybe something similar would work for loading JavaScript, instead of the approach I outlined here: Loading main.js with defer. (Edit: I’m trying that approach now, but seem to be running into issues with auto-reloading changes in development.)

Tags: