Abhilash Meesala

Integrating Tailwind CSS with Hugo

There are two ways to integrate Tailwind CSS with Hugo

  1. Using Hugo’s PostCSS pipe, or
  2. Using external NPM scripts

Getting started with PostCSS pipe is easy, but you’ll occasionally run into subtle bugs.

For this site, I use NPM scripts. It’s pretty straightforward to set up and works well. Here’s how to do it.

  1. Initialize npm in your site directory npm init -y

  2. Add Tailwind to your project and initialize it. For v3, the installation commands are these.

    npm install -D tailwindcss
    npx tailwindcss init
  3. Create input.css file containing Tailwind CSS directives under the theme assets directory ./themes/YOUR_THEME/assets/css/input.css.

    /* ./themes/YOUR_THEME/assets/css/input.css */
    @tailwind base;
    @tailwind components;
    @tailwind utilities;
  4. Configure Tailwind to look for sources in your theme and layouts directory.

    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./themes/YOUR_THEME/**/*.html",
        "./layouts/**/*.html",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
  5. Install the npm-run-all utility

    npm install -D npm-run-all
  6. Update your package.json scripts section to the following

    "scripts": {
      "dev:css": "npx tailwindcss -i themes/YOUR_THEME/assets/css/input.css -o themes/YOUR_THEME/assets/css/output.css",
      "dev:hugo": "hugo serve -D",
      "dev": "npm-run-all dev:css --parallel 'dev:* -- --watch'",
      "build:css": "NODE_ENV=production npx tailwindcss -i themes/YOUR_THEME/assets/css/input.css -o themes/YOUR_THEME/assets/css/output.css",
      "build:hugo": "hugo --gc --minify",
      "build": "run-s build:css build:hugo"
    },
  7. The above scripts generate an output.css file under the theme assets directory. You need to edit the head tag of your theme to pull in this generated CSS file. Usually, everything inside ./themes/YOUR_THEME/layouts/partials/head.html is included in the base template, so add the following at the end of that file

    {{ $css := resources.Get "css/output.css" }}
    {{ if hugo.IsProduction }} {{ $ccs  = $ccs | minify | resources.Fingerprint }} {{end}}
    <link href="{{ $css.RelPermalink }}" rel="stylesheet"  {{ if hugo.IsProduction }}  integrity={{ $css.Data.Integrity }} {{end}} />

That’s it. Use the dev command (npm run dev) to spin up Tailwind CLI and Hugo in watch mode. Use the build command(npm run build) to build for production.