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.
hugo new site hugotails
hugo new theme tailwind-theme
// hugo.toml
baseURL = 'http://example.org/'
languageCode = 'en-us'
title = 'My New Hugo Site'
theme = "tailwind-theme"
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: []
};
// input.css
@tailwind base;
@tailwind components;
@tailwind utilities;
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.
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.