How to set up a blog using Hexo and Github

Hexo

Installation hexo-cli

1
npm install -g hexo-cli

Setup

  1. 在 github 上建立一個 private repository,用作儲存 blog 的 source。New Repository
  2. 再建立一個 public repository 是 github pages 用作 static website
1
2
3
hexo init blog
cd blog
npm install

Modify package.json

可以加入 debug,用作 run server 並且顯示 draft

1
2
3
4
5
6
7
8
9
{
"scripts": {
"build": "hexo generate",
"clean": "hexo clean",
"deploy": "hexo clean && hexo deploy",
"server": "hexo server",
"debug": "hexo server -w --draft --open"
}
}

Configuration

詳細可以參考官方文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Site
title: Sean's blog
subtitle: Senior Engineer
description: ''
keywords:
author: Sean Cheng
language: en
timezone: 'Asia/Taipei'

# URL
## If your site is put in a subdirectory, set url as 'http://yoursite.com/child' and root as '/child/'
## The URL of your website, must starts with http:// or https://
url: https://blog.seancheng.space/

# Writing
post_asset_folder: true

# Deployment
## Docs: https://hexo.io/docs/deployment.html
deploy:
type: git
repo: ${YOUR_GITHUB_PAGE_REPO_WITH_SSH}
branch: master

CNAME

建立一個名為 CNAME file,用作定義 Github pages custom domain

1
echo 'blog.seancheng.space' > ./source/CNAME

Deployment

使用 Github Action 部署到 Github pages

  1. 建立一對 rsa key

    1
    ssh-keygen -t rsa -b 4096 -f blog-deploy-key -C blog
  2. Github pages repository 中的 Settings -> Deploy keys 新增上一步驟產生出來的公鑰,名為 HEXO_DEPLOY_PUB,記得勾選 Allow write access

  3. 在 blog 的 private repository 中的 Settings -> Secrets 新增私鑰,名為 HEXO_DEPLOY_PRI

  4. 在 blog 的 private repository 中新增 workflows yaml file

    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
    # .github/workflows/main.yml
    name: Deploy

    on: [push]

    jobs:
    build:
    runs-on: ubuntu-latest
    name: A job to deploy blog.
    steps:
    - name: Checkout
    uses: actions/checkout@v1
    with:
    submodules: true

    # Caching dependencies to speed up workflows. (GitHub will remove any cache entries that have not been accessed in over 7 days.)
    - name: Cache node modules
    uses: actions/cache@v1
    id: cache
    with:
    path: node_modules
    key: ${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}
    restore-keys: |
    ${{ runner.os }}-node-
    - name: Install Dependencies
    if: steps.cache.outputs.cache-hit != 'true'
    run: npm install

    # Deploy hexo blog website.
    - name: Deploy
    id: deploy
    uses: sma11black/[email protected]
    with:
    deploy_key: ${{ secrets.HEXO_DEPLOY_PRI }}

How to use

以下使用 command line

New

draft 也可以改成 post 或是其他的

1
hexo new draft "${YOUR_POST_TITLE}"

Publish

publish 其實就是將 draft 移動到 post

1
hexo publish "${YOUR_DRAFT_TITLE}"

Deploy

設定完 Hexodeploy後,可以直接使用 command line 進行部署

1
2
3
npm run deploy
# or
hexo clean && hexo deploy