0%

通过 Github Actions 部署 Github Pages

在项目的 settings 中 github pages 可以通过根目录或docs目录部署。但是这种方式不够灵活,对于一些前段项目,需要不停的通过CI生成站点文件,提交到git中再部署,git中存储了许多构建产物,显得冗余臃肿。

实际上,github也支持通过actions来部署pages,不需要将站点文件储存在git中。

要通过actions部署pages,需要如下步骤:

  1. 在workflow中构建站点文件,并保存到一个目录中
  2. 调用tar命令将构建好的站点目录打包为tar包,注意此时只打包不要做压缩
  3. 调用actions/upload-artifactaction将打包好的tar包上传到artifact,注意name参数必须为github-pages,path 参数为你tar包的路径
  4. 调用actions/deploy-pages即可将tar包中的内容作为站点内容部署

Bangumi Tracker项目中就使用了这个构建方式。
网站链接为https://bangumi.maple.link。

以下workflow展示了安装npm和yarn依赖,构建站点,tar打包,上传的过程。

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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
name: Build CI/CD

on:
push:
branches: [ "main" ]

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
pages-ci-cd:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ inputs.source_branch }}
- name: Set Node.js 20.x
uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
cache-dependency-path: app/yarn.lock
- name: Run install
uses: borales/actions-yarn@v4
with:
dir: 'app'
cmd: install # will run `yarn install` command
- name: Generate Protobuf
run: ./generate_proto_ts.sh
- name: Build
run: |
cd app
yarn build
- name: Archive artifact
shell: sh
run: |
echo ::group::Archive artifact
tar \
--dereference --hard-dereference \
--directory "app/build" \
-cvf "artifact.tar" \
--exclude=.git \
--exclude=.github \
.
echo ::endgroup::

- name: Upload artifact
id: upload-artifact
uses: actions/upload-artifact@v4
with:
name: github-pages
path: artifact.tar
retention-days: 1
if-no-files-found: error
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4