Please enable Javascript to view the contents

Hugo+Github Pages+Github Action博客自动发布方案

 ·  ☕ 2 分钟 · 👀... 阅读

本篇文章,默认为已经配置好本地的Hugo环境。

为什么要配置Github Action

我的博客全部代码放在自己的github pages(xxx/xxx.github.io)仓库管理,public 文件由pages分支单独管理。仓库设置里就可以指定GitHub Pages分支为pages。

没有配置Github Action 之前我们要发布一篇文章,要经过以下步骤:

  1. 在本地写好md文章
  2. 用hugo构建文章到public目录下
  3. 把本地仓库推送到github
  4. 把public 推送到github

配置Github Action 后,我们就只需要把写好的md文章,提交到github,然后坐等网站跟新就可以了。

配置Github Action

在博客根目录下,创建Github Action配置文件 .github/workflows/pages.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
41
name: GitHub Pages❤
on:
  push:
    branches:
      - main
jobs:
  build-deploy:
    runs-on: ubuntu-20.04
    steps:
      - name: Check out source
        uses: actions/checkout@v3
        with:
          submodules: recursive 
          fetch-depth: 0
     
          
      - uses: actions/cache@v2
        with:
          path: /tmp/hugo_cache
          key: ${{ runner.os }}-hugomod-${{ hashFiles('**/go.sum') }}
          restore-keys: |
            ${{ runner.os }}-hugomod-
                        
      - name: Setup hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: "0.101.0" #
          # extended: true # 设置是否需要 extended 版本
          
      - name: Build
        run: hugo --theme=zzo --baseUrl="https://week8.fun/" #hugo 构建时选择模版设置URL

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          personal_token: ${{ secrets.PERSONAL_TOKEN }} 
          external_repository: xxx/xxx.github.io 
          publish_dir: ./public
#          keep_files: false
          publish_branch: pages
          cname: week8.fun

配置合适的token

  1. 在个人GitHub页面,依次点击Settings-> Developer settings-> Personal access tokens -> Tokens (classic) 进入

  1. 点击 Generate new token 然后点击 Generate new token (classic)
  2. 设置 Note
  3. 设置 ExpirationNo expiration(永不过期)
  4. Select scopes 选择 workflow
  5. 点击 Generate token 生成token
  6. 复制生成的 token ,注意一旦离开页面后续就无法查看,只能从新生成。
  7. 进入对应的 pages 项目下
  8. 选择 Secrets -> Actions 点击 New repository secret
  9. 设置 NamePERSONAL_TOKEN 并把刚刚生成的 Token 放入 Secret 点击 Add secret

整个过程就已经设置完成了。

本地的public目录就可以删除了。现在就可以写一篇md文章,用git命令push到github仓库,即可触发GitHub Action。等待几分钟就可以在网站上看到我们刚刚写的文章。

分享

Jade
作者
Jade
📚Learner🌐Web Developer


目录