Hugo 新建站点的一些必要配置

用Hugo新建站点时的一些必要配置,自己踩过很多坑……

取消指纹检查

有时候生成的部分资源会报错: Incorrect SHA256 value for integrity attribute with fingerprint function: “failed to find a valid digest

解决方法是在hugo.toml[params]中添加:

1[params]
2# 其他内容
3  [params.assets]
4    disableFingerprinting = true

这样设置可以禁用指纹检查,避免Hugo检测资源的完整性,从而避免报错。


配置自动生成文章目录的级别

hugo.toml[markup]中添加:

1[markup]
2# 其他内容
3  [markup.tableOfContents]
4    startLevel = 1
5    endLevel = 4
6    ordered = false # 是否自动多级编号

上述设置会自动生成1-4级标题的目录,并自动编号。


配置代码块高亮和行号等

hugo.toml[markup]中添加:

 1[markup]
 2# 其他内容
 3  [markup.highlight]
 4    codeFences = true
 5    guessSyntax = true  # 是否自动检测代码语言
 6    hl_Lines = ""
 7    lineNoStart = 1   # 设置起始行数
 8    lineNos = true  # 是否显示行号
 9    lineNumbersInTable = false
10    noClasses = true
11    tabWidth = 4

PS:这样配置后,如果使用Stack主题,在复制代码时会把行号也复制进去(奇奇怪怪的Bug)。我们需要修改themes/hugo-theme-stack-master/assets/ts/main.ts文件,找到以下内容:

1        highlights.forEach(highlight => {
2            const copyButton = document.createElement('button');
3            copyButton.innerHTML = copyText;
4            ...
5        });

我们把这个逻辑修改为:

 1        highlights.forEach(highlight => {
 2            const copyButton = document.createElement('button');
 3            copyButton.innerHTML = copyText;
 4            copyButton.classList.add('copyCodeButton');
 5            highlight.appendChild(copyButton);
 6
 7            const codeBlock = highlight.querySelector('code[data-lang]');
 8            if (!codeBlock) return;
 9
10            copyButton.addEventListener('click', () => {
11                // 获取代码文本并按行分割
12                const codeLines = codeBlock.textContent.split('\n');
13                // 移除每行开头的行号
14                const cleanedCode = codeLines.map(line => {
15                    return line.replace(/^\s*\d+/, '');
16                }).join('\n');
17
18                navigator.clipboard.writeText(cleanedCode)
19                    .then(() => {
20                        copyButton.textContent = copiedText;
21
22                        setTimeout(() => {
23                            copyButton.textContent = copyText;
24                        }, 1000);
25                    })
26                    .catch(err => {
27                        alert(err)
28                        console.log('Something went wrong', err);
29                    });
30            });
31        });

主要修改了几个点,首先我们要获取代码块的文本内容,然后按行分割,再移除每行开头的行号,最后再复制,从而避免复制代码时把行号也复制进去,同时又保留了代码的缩进。


配置 markdown 允许 HTML 标签

hugo.toml[markup]中添加:

1[markup]
2# 其他内容
3  [markup.goldmark]
4    [markup.goldmark.renderer]
5      unsafe = true  # 允许不安全内容(如 HTML 标签)
6      hardWraps = true  # 是否自动换行

这样会允许在 markdown 中使用 HTML 标签。

中文字数统计不准

在启用了字数统计或阅读时长估计时,需要在hugo.toml中添加:

1hasCJKLanguage = true

这样会告诉 Hugo 这是一个包含中文字符的站点,从而正确统计中文字数。