Hugo Tailwind Integration

2021-05-05 约 708 字 预计阅读 2 分钟

Hugo主题整合tailwind,Tailwind用来写样式可以剩下很多时间,大部分的常用样式都有实现,在Hugo中使用(主题)需要将tailwindcss整合到hugo中. 主要涉及到安装依赖包,配置站点,建立资源文件和相应的目录以及如何利用hugo的管道进行预处理,压缩等等

1. 前提条件

  • 必须安装好hugu(必须是扩展版本extended), 参考 Hugo Installation
  • 安装好NodeJs

2. 新建站点和theme

1
2
3
4
hugo new site examplesite
cd examplesite

hugo new theme yourtheme
1
2
3
# 在hugo的站点主目录下
npm init -y
npm install --save-dev autoprefixer postcss postcss-cli postcss-import tailwindcss

3. 修改站点配置文件config.toml

1
theme = "yourtheme"

4. 建立css资源文件的的目录

1
2
 mkdir -p  ./themes/yourtheme/assets/css/

5. 新建postcss配置文件和tailwind配置文件

1
2
3
themes/yourtheme/assets/css/postcss.config.js
themes/yourtheme/assets/css/tailwind.config.js
themes/yourtheme/assets/css/styles.scss

6. 修改style.scss

1
2
3
@import "node_modules/tailwindcss/base";
@import "node_modules/tailwindcss/components";
@import "node_modules/tailwindcss/utilities";

7. 在head.html里添加style

1
2
3
4
5
6
7
8
<!-- Styles -->
{{ $styles := resources.Get "css/styles.scss" | toCSS | postCSS (dict "config" "./assets/css/postcss.config.js") }}
{{ if .Site.IsServer }}
  <link rel="stylesheet" href="{{ $styles.RelPermalink }}">
{{ else }}
  {{ $styles := $styles | minify | fingerprint | resources.PostProcess }}
  <link rel="stylesheet" href="{{ $styles.Permalink }}" integrity="{{ $styles.Data.Integrity }}">
{{ end }}

稍作解释

  • $styles := resources.Get "css/styles.scss" 定义变量,并赋值为一个资源文件路径
  • | toCSS 使用hugo的管道将scss编译为css
  • | postCSS (dict "config" "./assets/css/postcss.config.js") 指定postcss的配置文件
  • 如果是服务器模式isServer,就用相对路径
  • 如果是生产环境,将资源文件压缩
  • 将资源文件签名,这样确保如果修改以后不会读取缓存的

8. 测试

在header.html里添加一个标签

1
2
3
<header class="w-full bg-red-300">
  <h1 class="text-center">Welcome to HugoTails!</h1>
</header>

运行测试

1
hugo server

9. 参考

参考: How to add TailwindCSS to your Hugo site

文章作者 : Cocding