20 Hexo API 开发网站教程 - CI/CD 自动化部署

20 Hexo API 开发网站教程 - CI/CD 自动化部署

在本节中,我们将讨论如何使用 CI/CD 工具实现 Hexo 博客的自动化部署。我们将使用 GitHub Actions 作为示例来展示整个流程的设置。

1. 准备工作

1.1 创建 Hexo 博客

如果你还没有创建 Hexo 博客,可以按照以下步骤快速创建:

1
2
3
4
5
6
7
8
9
10
11
# 安装 Hexo CLI
npm install -g hexo-cli

# 创建一个新的 Hexo 项目
hexo init my-blog

# 进入项目目录
cd my-blog

# 安装依赖
npm install

1.2 配置 GitHub 仓库

  1. 在 GitHub 上创建一个新的仓库(如 my-blog)。
  2. 将本地 Hexo 项目设置成 Git 仓库并推送到 GitHub。
1
2
3
4
5
6
7
8
9
10
# 初始化 Git 仓库
git init

# 添加远程仓库
git remote add origin https://github.com/yourusername/my-blog.git

# 提交并推送初始代码
git add .
git commit -m "Initial commit"
git push -u origin master

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
2
3
4
deploy:
type: git
repo: https://github.com/yourusername/my-blog.git
branch: gh-pages

确保用你的 GitHub 仓库 URL 替换 repo 字段中的内容。

3. 设置 GitHub Actions

3.1 创建工作流文件

在 Hexo 项目中,创建一个新的目录和工作流文件:

1
2
mkdir -p .github/workflows
touch .github/workflows/deploy.yml

3.2 编辑 deploy.yml 文件

使用以下内容编辑 deploy.yml 文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
name: Deploy Hexo Blog

on:
push:
branches:
- master # 监听 master 分支的 push 事件

jobs:
deploy:
runs-on: ubuntu-latest

steps:
- name: Checkout code
uses: actions/checkout@v2

- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '14' # 指定 Node.js 版本

- name: Install dependencies
run: |
npm install

- name: Build Hexo
run: |
npm run generate # 生成静态文件

- name: Deploy to GitHub Pages
run: |
npm run deploy # 使用定义的 deploy 脚本

3.3 添加 Secrets

为了安全地推送内容到 GitHub Pages,我们需要添加 GitHub 的 Personal Access Token(个人访问令牌)作为 Secrets。

  1. 进入你 GitHub 仓库的设置页面,找到 Secrets 部分。
  2. 点击 New repository secret,然后创建一个 DEPLOY_KEY,其值为你的 Personal Access Token。

你可以根据以下链接生成 Personal Access Token: GitHub Token

3.4 修改部署命令

deploy.yml 中,我们需要在 Deploy to GitHub Pages 步骤中添加环境变量,以便可以安全访问仓库:

1
2
3
4
5
- name: Deploy to GitHub Pages
env:
GITHUB_TOKEN: ${{ secrets.DEPLOY_KEY }}
run: |
npm run deploy # 使用定义的 deploy 脚本

4. 测试 CI/CD 部署

到此为止,所有配置已经完成。接下来,做一次代码提交,触发 CI/CD 流程:

1
2
3
git add .
git commit -m "Make some changes"
git push origin master

如果一切正常,你将在 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 自动化部署

https://zglg.work/hexo-api-tutorial/20/

作者

AI教程网

发布于

2024-08-08

更新于

2024-08-10

许可协议