最近打算更新下博客模板并优化下内容的发布流程,于是放弃了多年不更新的 Octopress,在目前比较流行的静态博客生成工具 Hexo 和 Hugo 之间选择了后者,主要看重的是 Hugo 在发布时速度比较快,并且依赖较少。

关于发布流程,首先打算使用持续集成服务来提高内容发布效率,简化操作步骤,以达到提交 Markdown 源文件到 GitHub 后就能够自动完成博客站点的部署,在 Travis CI 和 GitHub Actions 之间选择了后者,对我来说最看重的就是它可以复用别人写好的 Action 并根据自己的需要来组合使用。

安装 Hugo

建议使用 Homebrew 安装 Hugo

brew install hugo

新建站点

hugo new site blog

新建站点后进入 blog 目录,查看生成的文件及主要目录

  • archetypes 目录下会有个模板文件,新生成的文章会以此为模板

  • config.toml 网站配置文件

  • content 用来存放 Markdown 文件

  • layouts 存放 html 模板文件,如果使用了第三方模板,可以将 themes 里 layouts 目录下的 html 复制过来,然后在这里修改,hugo 会优先使用这个目录下的该文件,以后再更新 themes 下的模板文件时也不用担心文件冲突问题

  • data 存储数据文件供模板使用

  • public 生成的静态网站文件会放在这里

  • static 可以把图片等静态资源放这里

  • themes 存放网站主题文件

安装主题

Hugo 整理了很多开发者制作的主题,安装时直接将主题下载到刚创建的 themes 目录中就可以了,具体方式可参考各主题的介绍说明

cd blog
git init
git submodule add https://github.com/vaga/hugo-theme-m10c.git themes/m10c

修改 config.toml

baseURL = "https://lijingcheng.github.io"
languageCode = "zh-cn"
title = "风行's Blog"
theme = "m10c"
paginate = 10

[params]
  author = "风行"
  avatar = "images/avatar.png"
  description = "一直在学习的大龄程序员"
  [[params.social]]
    name = "github"
    url = "https://github.com/lijingcheng"
  [[params.social]]
    name = "instagram"
    url = "https://www.instagram.com/bj_lijingcheng/"

新建文章

hugo new posts/first.md

本地预览

hugo server -D

通过 http://localhost:1313 查看,发布文章之前需要将文章内的 draft 改为 false

发布文章

使用 GitHub Actions 将生成的静态页面发布到 Github Pages,首先要在本地生成 ssh deploy key

ssh-keygen -t rsa -b 4096 -C "your.email" -f gh-pages -N ""

在 GitHub 网站中打开项目的设置页面,将刚生成的 ssh 公钥添加到 Deploy Keys 并选择 Allow write access,然后将私钥添加到 Secrets,可以命名为 ACTIONS_DEPLOY_KEY,然后再把写好的角本放到仓库根目录下的 .github/workflow/deploy.yml 文件中,角本内容可以引用别人写好的。

name: github pages

# 当 hugo-branch 分支发生 push 事件时执行下面任务
on:
  push:
    branches:
      - hugo-branch

env:
  ACTIONS_ALLOW_UNSECURE_COMMANDS: true

jobs:
  build-deploy:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1
      with:
        submodules: true

    - name: Setup Hugo
      uses: peaceiris/actions-hugo@v2.3.1
      with:
        hugo-version: '0.61.0'

    - name: Build
      run: hugo --minify

    - name: add nojekyll
      run: touch ./public/.nojekyll

    - name: Deploy
      uses: peaceiris/actions-gh-pages@v2.5.1
      env:
        ACTIONS_DEPLOY_KEY: ${{ secrets.ACTIONS_DEPLOY_KEY }}
        PUBLISH_BRANCH: master
        PUBLISH_DIR: ./public