Hugo 推送到生产环境不构建 SCSS 的问题

为了给博客添加主题切换按钮,将原先通过媒体查询(@media query)实现的暗色模式切换到了用 CSS 类名(.dark)实现,在本地测试无误,但合并到 master 分支并在 VPS 上构建之后,却出现了问题——当系统配色方案是「暗色」时,就算主动将站内的主题切换为「亮色」,也仍然会保持暗色背景;反之,在系统亮色方案下,将站内主题切换为「暗色」,却没有这个问题。

排查后发现,在本地构建的 Hugo 网站没有这个问题,但是在 VPS 上构建的网站,仍然使用了老旧的 @media 媒体查询方案,即便源代码都是一样的,构建结果却有所不同。

在后续的开发中,发现了类似的问题:修改了 SCSS 文件,本地测试没有问题,但推送到生产环境后,在 VPS 上构建的网站却没有使用最新的 SCSS,仍然使用过时的样式。

Hugo 的构建缓存?

Hugo 的确会缓存资源文件,见文档。不过,一般来说只会在构建过程中缓存,避免在同一个构建过程中反复从磁盘中读取相同的文件;也会在多次构建之间缓存,但照例来说不会持续好几天都只能读取到旧文件。

以下是 Hugo 默认的缓存配置。

[caches]
  [caches.assets]
    dir = ':resourceDir/_gen'
    maxAge = -1
  [caches.getresource]
    dir = ':cacheDir/:project'
    maxAge = -1
  [caches.images]
    dir = ':resourceDir/_gen'
    maxAge = -1
  [caches.misc]
    dir = ':cacheDir/:project'
    maxAge = -1
  [caches.modulequeries]
    dir = ':cacheDir/modules'
    maxAge = '24h'
  [caches.modules]
    dir = ':cacheDir/modules'
    maxAge = -1

可见,除了模块查询(module queries)默认缓存一天之外,包括静态资源在内的其他内容都是默认没有缓存的(即值为 -1)。

那么就不会是构建缓存的问题了。也不可能是 Cloudflare 的网络层缓存,因为网站使用的是行内 CSS,是以 <style> 标签嵌入到 HTML 文件里的,不会被缓存。

尝试在 VPS 上手动构建

SSH 到 VPS 上,进入博客项目的根目录,直接运行 hugo,发现没有任何报错。

运行 hugo --ignoreCache,发现如下报错:

eltrac@vps:~/geedeapro$ hugo --ignoreCache
Start building sites …
hugo v0.156.0-DEV-24eb84f8681bc86a40c2b737969fb9b8292f26b7 linux/amd64 BuildDate=2026-02-06T14:06:19Z

Total in 303 ms
ERROR error building site: render: [zh v1.0.0 guest] failed to render pages: render of "/" failed: "/home/eltrac/geedeapro/layouts/baseof.html:3:3": execute of template failed: template: home.html:3:3: executing "home.html" at <partial "head.html" .>: error calling partial: "/home/eltrac/geedeapro/layouts/_partials/head.html:8:5": execute of template failed: template: _partials/head.html:8:5: executing "_partials/head.html" at <partial "head/css" .>: error calling partial: "/home/eltrac/geedeapro/layouts/_partials/head/css.html:20:10": execute of template failed: template: _partials/head/css.html:20:10: executing "_partials/head/css.html" at <.Content>: error calling Content: TOCSS: failed to transform "/css/main.scss" (text/x-scss). Check your Hugo installation; you need the extended version to build SCSS/SASS with transpiler set to 'libsass'.: this feature is not available in your current Hugo version, see https://goo.gl/YMrWcn for more information

重点在这一段:

you need the extended version to build SCSS/SASS with transpiler set to 'libsass'.: this feature is not available in your current Hugo version

这里说必须要用拓展版 Hugo 才能构建 SCSS 文件。所以之前并不是 Hugo 故意缓存,而是因为没有解析 SCSS 文件的能力,所以不得不使用旧的数据(我记得我在 VPS 上重新安装过一次 Hugo,当是可能意外安装了没有拓展的版本)。

我是直接从源代码构建 Hugo 的,在构建时加上 extended 标签即可:

CGO_ENABLED=1 go build -tags extended .

不过,如果不是为了用最新版本还是不建议自己编译,因为 VPS 的 CPU 实在是太烂了,编译要好几分钟,而且 CPU 占用率一直居高不下,太可怕了……

使用拓展后的 Hugo 重新编译网站,发现问题解决。

2026-02-15