一文打通 Hexo 从 0 到上线:安装、建站、换主题、写作、部署,以及我真实遇到的报错与解决方案(Pug 模板未渲染)。
为什么选 Hexo?
- 生成快、部署简单、主题超多(NexT/Butterfly/Volantis/Fluid…)
- Markdown 写作友好,插件齐全(评论、搜索、统计、RSS)
环境准备
要求: Node.js(建议 LTS ≥ 18)、Git
安装检查:
1 | node -v |
初始化站点
1 | hexo init myblog |
核心目录:
1 | . |
写第一篇文章 & 本地预览
1 | hexo new "Hello World" |
更换漂亮主题(以 Butterfly 为例)
1 | git clone -b master https://github.com/jerryc127/hexo-theme-butterfly themes/butterfly |
在站点根目录 _config.yml 里设定:
1 | theme: butterfly |
预览:
1 | hexo clean && hexo g && hexo s |
🚨 踩坑记录:页面直接显示 Pug 源码(未渲染)
现象:
浏览器页面不是主题样式,而是原样显示:
1 | extends includes/layout.pug |
根因:
Hexo 没有启用 Pug 渲染器,导致 .pug 模板被当作纯文本输出。
**解决:**在站点根目录安装渲染器插件(很多主题必需)
1 | npm install hexo-renderer-pug --save |
然后重试:
1 | hexo clean && hexo g && hexo s |
刷新页面即可正常渲染主题 🎉
附加排查:
- 确认
_config.yml里的theme:与themes/下的目录同名 - 看
themes/<你的主题>/layout/文件扩展名,若是.pug就必须装hexo-renderer-pug - 仍异常 → 再
hexo clean后启动;必要时删除.deploy_git/与public/重新生成
常用命令速查
| 命令 | 说明 |
|---|---|
hexo new "标题" |
新建文章(在 source/_posts/) |
hexo server / hexo s |
本地预览 |
hexo generate / hexo g |
生成静态文件到 public/ |
hexo clean |
清理缓存与旧构建 |
hexo deploy / hexo d |
部署(安装部署插件后可用) |
一键部署到 GitHub Pages
1)安装部署插件:
1 | npm install hexo-deployer-git --save |
2)配置 _config.yml:
1 | deploy: |
3)部署:
1 | hexo clean && hexo g && hexo d |
访问:https://你的用户名.github.io
常见问题:
- 404 或空白:检查仓库名是否为
username.github.io,分支设置是否匹配 - 样式丢失:确认
_config.yml的url:写对(含https://与自定义域名时的正确域)
常用插件推荐
1 | npm i hexo-generator-sitemap --save # 站点地图 |
进阶:GitHub Actions 自动构建发布
推荐方案:使用 GitHub Pages 部署(2025年最佳实践)
在你的仓库中新增 .github/workflows/pages.yml:
1 | name: Build and Deploy to GitHub Pages |
重要配置:
- 启用 GitHub Pages:Settings → Pages → Source 选择 “GitHub Actions”
- 更新
_config.yml:1
url: https://username.github.io/repo-name
- 移除 hexo-deployer-git:不再需要传统的 git 部署
以后只需 git push,自动发布到 https://username.github.io/repo-name。
⚠️ 注意:如果遇到 hexo: command not found 错误,确保使用 npx hexo 而不是 hexo。
主题与功能个性化建议
- 评论:Giscus / Waline / Utterances
- 统计:Google Analytics / Cloudflare Web Analytics / 不蒜子
- 搜索:
hexo-generator-searchdb+ 本地搜索脚本 - 封面与摘要:多数主题支持
excerpt、cover字段,按主题文档配置
完整命令回顾(可复制)
1 | # 1. 安装 |
结语
如果你也遇到“页面显示 Pug 源码”的问题,十有八九就是 缺少 hexo-renderer-pug。按上文安装并清理重启,基本一次解决。其余个性化配置(评论/搜索/统计/CDN/图床)可按主题文档循序渐进添加。