如果你曾了解过 Hexo https://hexo.io/zh-cn/ , 相信你已经可以通过 hexo deploy 部署自己的博客到 GitHub pages 了.
但是, 这样我们仅仅可以通过当前电脑来发布博客, 如果电脑不在身边, 或者不小心把文件删除了, 就会很麻烦.
本文教你如何实现把自己写的博客和生成的静态文件同时托管在 GitHub:
将博客源码托管到 GitHub
细心的人可以发现, 通过 hexo init 生成的文件中, 已经包含了. gitignore 文件. 说明 hexo 开发者也是希望大家把博客源码托管到 Git 上的.
我们可以通过分支来实现, 将源码放在 master(看个人喜好) 分支, 将 hexo deploy 的分支指定为 gh-pages 分支. 具体实现如下:
如果没有 GitHub repository 首先需要在 GitHub 新建一个仓库, 点击 new repository.
hexo init 生成一个新的博客项目
根据 hexo 文档 https://hexo.io/zh-cn/docs/configuration.html 修改配置, 使博客可以通过 Git server 预览.
Git init
Git remote add origin Git@GitHub.com:account/blog_repo.Git 请将 Git 地址改为 1 中说到的你自己的仓库地址
- Git add .
- Git commit -m "init"
Git push origin master -f 将代码推到 GitHub master 分支
这时候, 我们就把项目托管到了 GitHub, 当你换了一台电脑, 或者不小心把文件删除了的时候, 只要重新 Git clone 就可以了.
但是这仅仅只是将代码托管到了 GitHub. 当我们新完成一篇博客, 并把代码push 到 GitHub 上的时候, 并不会自动 deploy.
通过 travis 自动部署
Travis CI https://travis-ci.org/ 是在软件开发领域中的一个在线的, 分布式的持续集成服务, 用来构建及测试在 GitHub 托管的代码.
使用 GitHub 授权登录 Travis CI https://travis-ci.org/
在 Travis CI 中打开博客项目仓库的开关. 并在配置中打开 Build only if .travis.YAML is present 选项
在 GitHub 中创建 access token, 详细教程: Creating a personal access token for the command line
在 travis 博客仓库的配置中将刚刚生成的 token 添加到 Environment Variables 中, name 为 REPO_TOKEN
在项目根目录新增. travis.YAML 文件. 配置如下
- language: node_js
- node_js: stable
- branches:
- only:
- - master
- cache:
- directories:
- - node_modules
- before_install:
- - Git config --global user.name "sjfkai"
- - Git config --global user.email "sjfkai@163.com"
- - NPM install -g hexo-cli
- - export HEXO_DEPLOYER_REPO=https://$REPO_TOKEN@GitHub.com/sjfkai/blog.Git
- install:
- - NPM i
- script:
- - hexo clean
- - hexo generate
- - hexo deploy
修改 hexo 的配置文件_config.YAML 的 deploy:
- # 注意, 这里注释掉了 repo, 因为我们需要在 ci 中通过环境变量 HEXO_DEPLOYER_REPO 配置
- deploy:
- type: Git
- # repo:
- branch: gh-pages
- Git add .
- Git commit -m "add travis ci"
- Git push origin master
这时候你会发现 travis ci 显示该项目处于 running 状态. 等最后变为 passed 状态后. GitHub pages 就已经自动部署成功了.
博主源码
https://github.com/sjfkai/blog
来源: https://juejin.im/post/5c887419e51d45334d2f9a00