20 Hexo API 开发网站教程 - CI/CD 自动化部署
在本节中,我们将讨论如何使用 CI/CD 工具实现 Hexo 博客的自动化部署。我们将使用 GitHub Actions 作为示例来展示整个流程的设置。
1. 准备工作
1.1 创建 Hexo 博客
如果你还没有创建 Hexo 博客,可以按照以下步骤快速创建:
1 | # 安装 Hexo CLI |
1.2 配置 GitHub 仓库
- 在 GitHub 上创建一个新的仓库(如
my-blog
)。 - 将本地 Hexo 项目设置成 Git 仓库并推送到 GitHub。
1 | # 初始化 Git 仓库 |
2. 配置 Hexo 部署
2.1 安装 Hexo 部署插件
在 Hexo 项目中,我们需要安装 hexo-deployer-git
插件,以便将生成的博客内容部署到 GitHub Pages。
1 | npm install hexo-deployer-git --save |
2.2 配置 _config.yml
文件
编辑 Hexo 博客根目录下的 _config.yml
文件,添加以下内容:
1 | deploy: |
确保用你的 GitHub 仓库 URL 替换 repo
字段中的内容。
3. 设置 GitHub Actions
3.1 创建工作流文件
在 Hexo 项目中,创建一个新的目录和工作流文件:
1 | mkdir -p .github/workflows |
3.2 编辑 deploy.yml
文件
使用以下内容编辑 deploy.yml
文件:
1 | name: Deploy Hexo Blog |
3.3 添加 Secrets
为了安全地推送内容到 GitHub Pages,我们需要添加 GitHub 的 Personal Access Token(个人访问令牌)作为 Secrets。
- 进入你 GitHub 仓库的设置页面,找到
Secrets
部分。 - 点击
New repository secret
,然后创建一个DEPLOY_KEY
,其值为你的 Personal Access Token。
你可以根据以下链接生成 Personal Access Token: GitHub Token
3.4 修改部署命令
在 deploy.yml
中,我们需要在 Deploy to GitHub Pages
步骤中添加环境变量,以便可以安全访问仓库:
1 | - name: Deploy to GitHub Pages |
4. 测试 CI/CD 部署
到此为止,所有配置已经完成。接下来,做一次代码提交,触发 CI/CD 流程:
1 | git add . |
如果一切正常,你将在 GitHub Actions 的界面上看到构建过程,并在成功后,访问你的博客链接(例如 https://yourusername.github.io/my-blog/
)查看更改。
5. 常见问题
- 构建失败: 检查 GitHub Actions 日志,确保没有错误。常见错误包括 Node.js 版本不兼容或缺少依赖。
- 无法访问博客: 确保 GitHub Pages 在仓库设置中已启用,并且指定的分支(通常为
gh-pages
)未被删除。
通过以上步骤,你可以成功设置 Hexo 博客的 CI/CD 自动化部署。这将极大地方便你的内容更新和发布流程!
20 Hexo API 开发网站教程 - CI/CD 自动化部署