前言

本博客使用 Travis CI 实现自动化部署,更新博客只需将文章 push 到 Github 上即可触发构建,生成静态文件并推送到 Github Pages。

准备工作

我使用了 2 个 Github 仓库,一个私有仓库用于备份 Hexo 博客的源码,另一个公开仓库就是 Github Pages;另外,需要注意的是私有项目要使用 travis-ci.com,而不是 travis-ci.org(针对公开项目)。

本博客备份的文件结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
├── .gitignore
├── .travis.yml
├── _config.yml
├── _config.butterfly.yml
├── package.json
├── scaffolds
│   ├── draft.md
│   ├── page.md
│   └── post.md
├── source
│   ├── robots.txt
│   ├── _data
│   ├── _posts
│   ├── about
│   ├── categories
│   ├── link
│   ├── music
│   └── tags
└── themes
├── butterfly
└── landscape

Travis CI 配置

安装 GitHub Apps —— Travis CI

根据官方教程(将 Hexo 部署到 GitHub Pages)添加 Travis CI;

点击齿轮图标进行配置,这里只授权访问用于备份博客的私有仓库。

Travis CI 环境变量配置

在 Github 的设置页面新建 Personal Access Token,起个名称并勾选仓库权限;

注意:token 生成后只会显示一次,请务必即时保存。

travis-ci.com 站点上进行配置,点击打开相应的仓库,选择 Settings 添加环境变量,名称 GH_TOKEN ,值就是在 Github 上生成的 Personal Access Token,其余使用默认配置即可。

.travis.yml 配置

在博客根目录下新建 .travis.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
32
33
34
35
36
37
38
39
40
# nodejs 为了支持豆瓣插件用 12
language: node_js
node_js:
- 12

# 缓存,加快构建速度
cache:
yarn: true
directories:
- node_modules

# 将博客更新到 master 分支
branches:
only:
- master

# 构建前,设置时区、github 用户名和账号
before_install:
- export TZ='Asia/Shanghai'
- git config --global user.name "jckling"
- git config --global user.email "jckling@163.com"

# 安装依赖模块
install:
- yarn install

# 构建脚本
# hexo-douban 用于生成本博客的 Movie 页面,详见主页右上角 List-Movie
script:
- hexo douban -m
- hexo generate

# 将生成的博客静态文件 push 到 Github Pages 仓库
after_script:
- git clone https://github.com/jckling/jckling.github.io.git
- cp -r ./public/* ./jckling.github.io/
- cd jckling.github.io
- git add .
- git commit -m "Travis-CI Automated Deployment $(date +'%Y-%m-%d %H:%M:%S')"
- git push "https://${GH_TOKEN}@github.com/jckling/jckling.github.io.git" master

结果检验

更新后将博客 push 到 Github 上,触发自动构建,可在 travis-ci.com 上查看详细过程。

另外提醒一句,这样的提交方式会使得 Github Pages 仓库始终只有一次提交(Commit),如果想要保留 Commit 记录的话就得 clone - add - comment - push,修改 .travis.yml 文件 after_script 部分的内容即可。

参阅