无题/Hugo+Github Action自动部署静态页面

Created Sat, 22 May 2021 17:37:27 +0800 Modified Wed, 13 Dec 2023 07:03:38 +0000
1102 Words

Hugo

Hugo is one of the most popular open-source static site generators. With its amazing speed and flexibility, Hugo makes building websites fun again.

安装

如果你是Windows用户,可以直接从Github Release页面下载对应的版本即可

如果你是Linux用户则有三种方式来安装Hugo

在这介绍下自行编译,最新的Hugo使用到了go1.16io/fs包,因此如果想自行编译最新版本的Hugo则要安装或更新系统go版本至1.16+。安装完语言编译环境后按以下步骤进行

mkdir $HOME/src
cd $HOME/src
git clone https://github.com/gohugoio/hugo.git
cd hugo
go install

如果你想让Hugo支持sass的话则需要编译另一个版本

CGO_ENABLED=1 go install --tags extended

在终端中输入hugo version来检查是否编译成功

创建站点

安装完Hugo后就可以来创建一个网站站点,假设名称为demo

hugo new site demo
cd demo
git init

在初始化站点后,需要为站点选择一个主题,这里选择我使用的Hermit

git submodule add https://github.com/Track3/hermit.git themes/hermit
cp themes/hermit/exampleSite/config.toml .

随后创建一篇新文章

hugo new posts/Hello-hugo.md

添加完文章后输入以下指令进行预览

hugo server -D

预览图

Github Action自动化发布

当完成一个站点之后,可以发布到github page中,在这介绍如何使用Github Action来自动化部署站点到github page中

Github Page分为用户Page和项目Page,用户Page通常为username.github.io而项目Page通常为username.github.io/project,但也可以通过添加CNAME文件来自定义域名,在这展示项目Page

首先创建一个项目(Repository),假设为demo记住要设置为公开,然后在你的站点的根目录创建以下文件并写入

# .github/workflows/gh-pages.yml
name: github pages

on:
  push:
    branches:
      - master  # 要编译的文件分支
  pull_request:

jobs:
  deploy:
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
        with:
          submodules: true  # Fetch Hugo themes (true OR recursive)
          fetch-depth: 0    # Fetch all history for .GitInfo and .Lastmod

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: 'latest'
          extended: true

      - name: Build
        run: hugo --minify

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./public

在部署到Github之前,还需要更改Hugo的根配置,将config.toml中的baseURL更改为https://{username}.github.io/demo,如果配置了域名则为https://{CUSTOM_DOMAIN}/demo

随后,将你的站点所有文件push到Github中

git remote add origin https://github.com/{your_user_name}/{your_project}.git
git add .
git commit -m "Upload"
git push -u origin master

这时,前往你的项目页面查看Actions标签查看编译结果,如果成功则如下所示

Action

完成编译之后,还不能立刻通过网址来访问,需要在项目的Settings\Pages中,选择Github Page的来源,在这选择gh-pages

设置成功后访问https://{username}.github.com/{project_name}即可,如果配置了CNAME则通过https://{CUSTOM_DOMAIN}/{project_name}即可

结果