How to setup Tailwind CSS in Hugo?

Published 27 May, 2022

Reading time: 2 Mins


Hugo Tailwind CSS theme - Lets see how we can integrate Tailwind CSS to Hugo project.

Creating a new Hugo project.

First let’s setup the project. If you already have the project then don’t worry you can skip this part.

hugo new site project-tailwind

cd project-tailwind

Setting up the Tailwind CSS

Install these packages from NPM and configure postcss.config.js and then tailwind.config.js

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

Init command will create a new tailwind.config.js file and update that file with below content.

module.exports = {
  mode: "jit",
  content: [
    "./content/**/*.md",
    "./layouts/**/*.html",
  ],
  theme: {
    extend: {}
  },
  plugins: [
    require('@tailwindcss/typography'),
  ]
}

Once you update the Tailwind config then create a new PostCSS file next to Tailwind CSS config file.

// touch postcss.config.js
module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  }
}

Once that done now it’s time to configure the Hugo pipe feature so that whenever file change happen in project folder Hugo will run the PostCSS plugin and run the Tailwind. And finally the updated CSS file will available in the browser.

Create assets folder if not in your project root and create tailwind.css file.

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

Configure Hugo Pipe to PostCSS Tailwind CSS

Create a new html file inside the partial folder. If you don’t have the folder for the new project then please create it in either layout or in the theme folder. I am going to call that as the css.html. And update that with this below code.

{{ $styles := resources.Get "css/tailwind.css" }}
{{ $styles = $styles | resources.PostCSS }}
{{ if hugo.IsProduction }}
  {{- with $styles -}}
    <style>{{- .Content | safeCSS -}}</style>
  {{- end -}}
{{ else }}
  {{ $styles = $styles | resources.ExecuteAsTemplate (printf "css/index.dev.%v.css" now.UnixMilli) .}}
  <link href="{{ $styles.RelPermalink }}" rel="stylesheet" />
{{ end }}

At this moment that I wrote this article there is no direct support from Hugo to run the Tailwind CSS so we need to rely on the partialcache.

In your base.html or index.html place the code inside the head tag

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

Conclusion

We saw what are the packages that needs to be installed in the NPM and how to create a folder structure in Hugo. And finally configuring tailwind.confg.js to configure the tailwind end.

Also there is Github repo I created to the codebase.

This article published under development on hugo tags. If you wish to receive email from me when I post a new blog post then please subscribe to my newsletter.


You might also like