shou2017.com
JP

Applying TailwindCSS to Hugo

Tue Jan 2, 2024
Sat Aug 10, 2024

When it comes to applying TailwindCSS to Hugo, many guides use postcss as a pipe, but in my experience, most of those cases didn’t work properly. So, I tried applying TailwindCSS to Hugo by building TailwindCSS without using postcss.

Environment

  • Hugo v0.115.2+extended darwin/amd64 BuildDate=unknown
  • TailwindCSS 3.4.0

Create a new Hugo site

hugo new site hugotails

Create a Hugo theme

hugo new theme tailwind-theme

Apply the theme

// hugo.toml
baseURL = 'http://example.org/'
languageCode = 'en-us'
title = 'My New Hugo Site'
theme = "tailwind-theme"

Install TailwindCSS

Run the following commands in the root directory:

npm install -D tailwindcss
npx tailwindcss init

tailwind.config.js will be created. By specifying the Hugo theme path in the content property, unnecessary TailwindCSS code will be removed. This reduces the file size at build time.

// tailwind.config.js
module.exports = {
  content: ["./themes/tailwind-theme/layouts/**/**.html"],
  theme: {
    extend: {}
  },
  variants: {},
  plugins: []
};

Add Tailwind directives

// input.css
@tailwind base;
@tailwind components;
@tailwind utilities;

Build with Tailwind CLI

Once everything is set up, build using the Tailwind CLI command:

npx tailwindcss -i ./themes/tailwind-theme/assets/css/input.css -o ./themes/tailwind-theme/assets/css/output.css

After running the command, output.css will be created in the same directory as input.css. Ensure that only the classes used in Tailwind are included in the output.

Edit Hugo templates

Load the output.css you just created into Hugo templates and check if it displays correctly.

Edit the theme’s index.html:

<!-- themes/tailwind-theme/layouts/index.html -->
{{ define "main" }}
  <h1 class="text-3xl font-bold underline">Hello world! ここが変更</h1>
{{ end }}

Edit the theme’s baseof.html:

<!-- themes/tailwind-theme/layouts/_default/baseof.html -->
<!DOCTYPE html>
<html>
  {{- partial "head.html" . -}}
  <body class="bg-gray-800 text-gray-50">
    {{- partial "header.html" . -}}
    <div id="content">{{- block "main" . }}{{- end }}</div>
    {{- partial "footer.html" . -}}
  </body>
</html>

Edit the theme’s head.html to include output.css:

<head>
  <!-- themes style -->
  {{ with resources.Get "css/output.css"}}
  <link rel="stylesheet" href="{{ .RelPermalink }}" />
  {{ end }}
</head>

Start the server and check if everything is displayed correctly.

HugoにTailwindCSSを適用する

See Also