2025-02-12 19:15:28 +08:00

3.9 KiB
Raw Permalink Blame History

title description date categories tags lastmod
Hugo 新建站点的一些必要配置 用Hugo新建站点时的一些必要配置自己踩过很多坑…… 2025-02-11
奇技淫巧
Hugo
配置
建站
2025-02-11T23:56:00+08:00

取消指纹检查

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

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

[params]
# 其他内容
  [params.assets]
    disableFingerprinting = true

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


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

hugo.toml[markup]中添加:

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

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


配置代码块高亮和行号等

hugo.toml[markup]中添加:

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

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

        highlights.forEach(highlight => {
            const copyButton = document.createElement('button');
            copyButton.innerHTML = copyText;
            ...
        });

我们把这个逻辑修改为:

        highlights.forEach(highlight => {
            const copyButton = document.createElement('button');
            copyButton.innerHTML = copyText;
            copyButton.classList.add('copyCodeButton');
            highlight.appendChild(copyButton);

            const codeBlock = highlight.querySelector('code[data-lang]');
            if (!codeBlock) return;

            copyButton.addEventListener('click', () => {
                // 获取代码文本并按行分割
                const codeLines = codeBlock.textContent.split('\n');
                // 移除每行开头的行号
                const cleanedCode = codeLines.map(line => {
                    return line.replace(/^\s*\d+/, '');
                }).join('\n');

                navigator.clipboard.writeText(cleanedCode)
                    .then(() => {
                        copyButton.textContent = copiedText;

                        setTimeout(() => {
                            copyButton.textContent = copyText;
                        }, 1000);
                    })
                    .catch(err => {
                        alert(err)
                        console.log('Something went wrong', err);
                    });
            });
        });

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


配置 markdown 允许 HTML 标签

hugo.toml[markup]中添加:

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

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

中文字数统计不准

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

hasCJKLanguage = true

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