Hugo搭建个人博客(4):更多更多(持续更新...)

目录

文章 Summary

文章简介 [img]

官方文档:https://gohugo.io/content-management/summaries/

推荐:自定义生成文章简介内容。

多语言支持,中文

defaultContentLanguage = "zh-cn"  # 这是关键配置
languageCode = "zh-cn"           # 这是SEO相关
hasCJKLanguage = true            # 启用中日韩语言支持

Waline 浏览数量统计

参考官网文档:https://waline.js.org/guide/features/pageview.html#%E5%92%8C%E8%AF%84%E8%AE%BA%E4%B8%80%E8%B5%B7%E4%BD%BF%E7%94%A8

可以根据自己的需求添加到对应位置。我提供我的修改,可以参考:

添加了一个新文件(themes/mainroad/layouts/partials/post_meta/pageview_count.html):

{{- if .RelPermalink }}
<div class="meta__item-pageview meta__item">
	{{ partial "svg/eye.svg" (dict "class" "meta__icon") -}}
	<span class="meta__text">
		阅读量:<span class="waline-pageview-count" data-path="{{ .RelPermalink }}" />
	</span>
</div>
{{- end -}}

在 index.html 添加如下内容:

{{ partial "pagination.html" . }}
......

<script type="module">
  import { pageviewCount } from 'https://unpkg.com/@waline/client@v3/dist/waline.js';
  
  document.querySelectorAll('.waline-pageview-count').forEach(el => {
    pageviewCount({
      serverURL: '{{ .Site.Params.waline.serverURL }}',
      path: el.dataset.path,
      update: (count) => {
        el.innerText = count;
      },
      update: false
    });
  });
</script>

......
{{ end }}

最后打开配置(config.toml):

[Params]
  post_meta = ["author", "date", "categories", "translations", "pageview_count"] # Order of post meta information

本地搭建 Waline

Waline 官方文档中的国际版我用了一周,感觉太慢了。我得寻找替代方案。 我在网上找了下,有大佬提到用腾讯得 CloudBase 搭建 Waline 的方法,我实际看了下,已经不实惠了。之前可以使用按量付费,现在腾讯修改了付费方式"基础套餐 + 按量付费",每月成本 19.9+。

所以我觉得就在我本地服务器搭建一个 Waline 服务。

步骤

1. 在本地服务器部署 Waline

官方文档:https://waline.js.org/guide/database.html#sqlite

开始没有看官方文档,折腾了我好久好久。

(1) 安装依赖环境
# 安装 Node.js 和 npm(以 Ubuntu 为例)
sudo apt update
sudo apt install -y nodejs npm
(2) 部署 Waline 服务端
# 创建项目目录
mkdir waline && cd waline

# 初始化项目
npm init -y
npm install @waline/vercel

# 创建启动文件 app.js
cat > app1.js <<EOF
// app.js
const http = require('http');
const Waline = require('@waline/vercel');

// 创建 Waline 处理器
const walineHandler = Waline({
  database: {
    dialect: 'sqlite',
    storage: './data/waline.sqlite',
  },
  // 强制禁用所有云服务
  disablePlatforms: ['*'],  // 使用通配符禁用所有平台 // 配置不生效
  // 或明确禁用所有可能平台
  // disablePlatforms: ['leancloud', 'mongodb', 'mysql', 'postgresql']
  enable: ['sqlite'], // 显式启用 SQLite
  // 阻止动态加载
  modules: {
    leancloud: null,
    mongodb: null,
    mysql: null
  }
});

// 创建 HTTP 服务
const server = http.createServer((req, res) => {
  walineHandler(req, res);
});

// 监听端口
const port = 8360;
server.listen(port, '0.0.0.0', () => {
  console.log(`Waline server running at http://0.0.0.0:${port}`);
});
EOF
(3) 启动 Waline

下载 https://github.com/walinejs/waline/blob/main/assets/waline.sqlite 数据库文件到 SQLITE_PATH 下

# 配置环境变量
export SQLITE_PATH=/home/ubuntu/waline/data
export JWT_TOKEN=aabbccdd # 随机字符串即可

DEBUG=waline:* node app.js
# 默认监听 8360 端口,可通过 Nginx 反向代理绑定域名

# 后台启动
nohup node app.js > app.log 2>&1 &
(4) Nginx 配置反向代理
server {
    listen 80;
    server_name yourdomain.com;

    # 原有博客静态文件配置
    location / {
        root /var/www/blog;
        index index.html;
    }

    # Waline 反向代理配置(子路径 /comment/)
    location /comment/ {
        # 关键:移除路径中的 /comment/ 前缀
        rewrite ^/comment/(.*)$ /$1 break;
        proxy_pass http://127.0.0.1:8360;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}
(5) 修改 Hugo config.toml 配置文件

[Params.waline]
    serverURL = "http://qinyangx.top/comment"

3. 配置开启自启动

(1)编辑文件
sudo vim /etc/systemd/system/waline.service

# 内容
# /etc/systemd/system/waline.service
[Unit]
Description=Waline Comment Service
After=network.target

[Service]
User=ubuntu
Wowaline.servicerkingDirectory=/home/ubuntu/waline
ExecStart=/usr/bin/node /home/ubuntu/waline/app.js
Restart=always
Environment=NODE_ENV=production
Environment=SQLITE_PATH=/home/ubuntu/waline/data
Environment=JWT_TOKEN=aabbccdd

[Install]
WantedBy=multi-user.target

(2)启动服务

sudo systemctl daemon-reload
sudo systemctl enable waline
sudo systemctl restart waline
sudo systemctl status waline  # 检查状态

sudo journalctl -u waline.service -b --no-pager # 查看错误日志

3. 可能遇到的问题

####### 执行node app.js报错,node版本过低
# 查看当前版本
node -v

# 使用 nvm 升级(如已安装)
nvm install --lts
nvm use --lts

# 或直接安装最新 LTS 版
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs

####### nvm不存在
# 下载并安装 nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash

# 激活 nvm(重新打开终端或运行)
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

####### node多个版本并存
# 查看当前生效的 node 路径(新版本)
which node
# 示例输出:/home/ubuntu/.nvm/versions/node/v18.16.0/bin/node

# 备份旧版本(可选)
sudo mv /usr/bin/node /usr/bin/node.bak

# 创建软链接指向新版本
sudo ln -sf $(which node) /usr/bin/node

# 验证版本
node --version       # 应显示新版本(如 v18.16.0)
/usr/bin/node --version  # 应与上面一致

最近访问统计只统计blog目录下

我的博客目录结构如下,Recent统计情况: content/ ├── blog/ # 默认被统计 ├── malangtaojin/ # 未被统计 └── math/ # 未被统计

只需要在 config.toml 中添加所有需要统计的目录:

[params]
  mainSections = ["blog", "news", "projects", "malangtaojin", "math"]  # 添加所有需要统计的目录,多余的可以不管

如何让自定义的css/js生效

找到/修改/添加config.toml中的配置:

...
  customCSS = ["css/custom.css"] # Include custom CSS files
  customJS = ["js/custom.js"] # Include custom JS files
...

这个配置的意思就是把static/css/custom.css打包进项目

hugo --gc --minify --cleanDestinationDir

源码: baseof.html

...
	{{ $style := resources.Get "css/style.css" | resources.ExecuteAsTemplate "css/style.css" . -}}
	<link rel="stylesheet" href="{{ $style.RelPermalink }}">
  
  <!--遍历配置,
  {{ . }}:当前遍历到的 CSS 文件路径(如 "css/custom.css")。
  | relURL:Hugo 的管道过滤器,将路径转换为正确的相对 URL(如 /css/custom.css)。-->
	{{ range .Site.Params.customCSS -}}
	<link rel="stylesheet" href="{{ . | relURL }}">
	{{- end }}
...