Hugo で tailwindcss を使う
はじめに
Hugo でテーマを作ってみようと思い、そのテーマに tailwindcss を使おうと思ったので色々調べたのでここにまとめておく
準備
$ hugo new site hugo-tailwindcss $ cd hugo-tailwindcss
必要なライブラリをインストールする
$ npm init -y $ npm install -D tailwindcss@latest \ @tailwindcss/typography \ postcss-cli@latest \ autoprefixer@latest \ @fullhuman/postcss-purgecss
設定ファイルを作る
PostCSS の設定ファイルを作成する
$ cat <<EOT > postcss.config.js const purgecss = require('@fullhuman/postcss-purgecss')({ content: ['./hugo_stats.json'], defaultExtractor: (content) => { let els = JSON.parse(content).htmlElements; return els.tags.concat(els.classes, els.ids); } }); module.exports = { plugins: [ require('tailwindcss'), require('autoprefixer'), ...(process.env.HUGO_ENVIRONMENT === 'production' ? [purgecss] : []) ] }; EOT
tailwindcss の設定ファイルを作成する
$ cat <<EOT > tailwindcss.config.js module.exports = { plugins: [ require('@tailwindcss/typography') ] } EOT
PurgeCSS のための設定ファイルを作成する。この設定により、ビルド時に hugo_stats.json
が作成される
$ mkdir -p config/production $ cat <<EOT > config/production/config.toml [build] writeStats = true EOT
hugo_stats.json
には以下のように、そのとき使われている HTML タグや CSS の class, id の情報が記載されている。PurgeCSS はこの情報を使って、使用されていない CSS のクラスを削除して、最終的に生成される CSS ファイルのサイズを削減できる
$ cat hugo_stats.json { "htmlElements": { "tags": [ "!doctype", "body", "div", "head", "html", "link", "meta", "title" ], "classes": [ "bg-gray-200", "bg-white", "flex", "font-extrabold", "h-screen", "items-center", "justify-center", "p-10", "rounded-xl", "shadow-xl", "text-6xl", "text-blue-500" ], "ids": null }
CSSやHTMLファイルを作る
$ mkdir assets $ cat <<EOT > assets/style.css @tailwind base; @tailwind components; @tailwind utilities; EOT
動作確認用に layouts/index.html
を作成して、上記で作成した CSS ファイルを読み込む
$ cat <<EOT > layouts/index.html <!DOCTYPE html> <html lang="{{ .Site.Language.Lang }}"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> {{ \$css := resources.Get "style.css" | resources.PostCSS }} {{ if hugo.IsProduction }} {{ \$css = \$css | minify | fingerprint | resources.PostProcess }} {{ end }} <link rel="stylesheet" href="{{ \$css.Permalink }}"> <title>{{ .Site.Title }}</title> </head> <body class="h-screen flex justify-center items-center bg-gray-200"> <div class="text-6xl text-blue-500 font-extrabold rounded-xl shadow-xl p-10 bg-white">Hello World</div> </body> </html> EOT
動作確認
最後に動作確認をする
$ hugo server -D --gc ... Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender Web Server is available at http://localhost:1313/ (bind address 127.0.0.1) Press Ctrl+C to stop ...
http://localhost:1313/
にアクセスして、下記の画面が表示できれば OK
今日の成果物