Featured image of post Hugo+Github从零基础到自动部署教程

Hugo+Github从零基础到自动部署教程

一、环境准备

1.1Git下载

前往【Git官网】,下载安装程序,一直点下一步,默认安装即可。

1.2 Hugo下载

前往【Hugo Github Tags】,选择对应版本下载,下载后解压即可,Windows下载版本:hugo_extended_withdeploy_xxxxx_windows_amd64.zip

二、搭建博客

2.1部署软件

将hugo.exe解压到D盘blog文件夹下,将该目录加入环境变量。

进入设置,系统-系统信息-高级系统设置-环境变量,编辑系统变量Path,加入hugo.exe根目录路径。

2.2创建博客

1)、在blog文件夹下,右键执行Git bash,执行以下命令。

2)、创建博客基本文件

1
hugo new site myblog

3)、进入myblog根目录

1
cd myblog

4)、运行本地博客

1
hugo server -D

5)、访问博客

访问http://localhost:1313,Ctrl+C停止服务。

目前显示Page Not Found,下面配置主题。

2.3配置主题

1)、前往hugo官网,选择自己喜欢的主题,进行下载。

2)、将下载好的主题解压,放到/themes文件夹中,删掉版本号,保留文件名。

3)、将主题下exampleSite样例数据中的 Content 和 hugo.yaml 复制到根文件夹中,并删掉hugo.toml。

4)、修改 hugo.yaml 中的 theme,将他修改为跟主题文件夹同名

5)、再次启动hugo服务,查看主题,具体主题配置修改hugo.yaml,这里不细说,感兴趣可自行查找相关文章

三、Github部署

3.1常规部署

1)、前往【Github官网】,创建仓库 {github用户名}.github.io

2)、前往Setting -> Pages -> Branch选择main分支,然后保存,会自动开启 https://{github用户名}.github.io 的地址,这地址也是以后访问博客的地址

3)、回到hugo文件中,执行命令hugo server -D,会生成 public 静态资源文件夹

4)、在 public 执行以下命令上传到github仓库上,第一次上传可能需要输入账号密码

1
2
3
4
5
6
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin {你的github仓库地址}
git push -u origin main

5)、上传成功后访问 https://{github用户名}.github.io,成功搭建属于自己的Hugo博客。

3.2Github Action自动部署

1)、Github创建一个新的仓库(建议选择私有),用于存放Hugo的源码主文件

2)、前往Setttings -> Developer Settings -> Personal access tokens,创建一个token(classic)

3)、token选择永不过期,并勾选 repo 和 workflow 选项

4)、为保证安全,将生成的token,保存的仓库的变量中,前往Settings -> Secrets and variables -> Actions中设置

5)、在hugo主文件创建一个.github/workflows/xxxx.yaml文件,将以下内容复制进去,想具体了解更多,可查看【Github Action文档

 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
name: deploy

# 代码提交到main分支时触发github action
on:
  push:
    branches:
      - main

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
        - name: Checkout
          uses: actions/checkout@v4
          with:
              fetch-depth: 0

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

        - name: Build Web
          run: hugo -D

        - name: Deploy Web
          uses: peaceiris/actions-gh-pages@v4
          with:
              PERSONAL_TOKEN: ${{ secrets.你的token变量名 }}
              EXTERNAL_REPOSITORY: 你的github名/你的仓库名
              PUBLISH_BRANCH: main
              PUBLISH_DIR: ./public
              commit_message: auto deploy

6)、在hugo主文件创建.gitignore文件,来避免提交不必要的文件

1
2
3
4
5
6
7
# 自动生成的文件
public
resources
.hugo_build.lock

# hugo命令
hugo.exe

7)、将hugo的主文件上传到仓库,上传成功后会触发Github Action,来自动部署你的静态页面

1
2
3
4
5
6
git init
git add .
git commit -m "first commit"
git branch -M main
git remote add origin {你的github仓库地址}
git push -u origin main

8)、以后每次发布执行以下命令即可

1
2
3
git add .
git commit -m "说明备注"
git push

9)、就可以将源码上传到github私有仓库里,并自动发布到网站仓库。

使用 Hugo 构建
主题 StackJimmy 设计
本博客已稳定运行
发表了10篇文章 · 总计5.93k字
本站访客数人次 本站总访问量