Hosting Hugo on Github

使用Hugo在Github上搭建个人博客

Posted by     "Daveedo" on Friday, October 19, 2018
1120 Words|Read in about 3 Min|Total Reading number of this article is times.

前期准备

要在Github上部署静态博客,首先需要准备好:

Github 页面种类

有两种Github页面可供选择:

  • 个人/组织页面

    (https://<USERNAME|ORGANIZATION>.github.io/)

  • 项目页面

    (https://<USERNAME|ORGANIZATION>.github.io/<PROJECT>/)

参考Github页面文档以便决定你将要部署的页面类型,这里选择比较简单的个人组织页面类型作为示例

个人/组织页面建立的分步教学

首先,个人/组织页面和项目页面的差别是:

  1. 必须用<USERNAME>.github.io来托管你用Hugo生成的内容

  2. master分支下的内容会被公开发布到你的Github主页上

分步教学

  1. 在Github上建立一个<YOUR-PROJECT>项目分支(例如,blog),这个分支会包含你的Hugo页面内容以及其他源文件

  2. 在Github上建立一个<USERNAME>.github.io,替换<USERNAME>为你的Github用户名。这个分支会包含你的Hugo页面的渲染版本。

  3. 在本地终端执行git clone <YOUR-PROJECT-URL> && cd <YOUR-PROJECT> ,克隆你在步骤1里建立的项目

  4. 确保网站在本地可以运行,在本地终端执行hugo serverhugo server -t <YOURTHEME>后用浏览器打开http://localhost:1313

  5. 确保网站内容可以发布后

    • CTRL+C来终止服务器

    • 执行rm -rf public移除public文件夹下全部内容(没有则可忽略)

  6. 执行git submodule add -b master git@github.com:<USERNAME>/<USERNAME>.github.io.git public 创建git 子模块。现在当你再执行hugo命令来部署网站到’public’时,建立的public目录则会在一个不同的Github分支下运作。

建立一键发布的脚本

现在,部署页面已经基本完成,你可以建立一个deploy.sh脚本来帮助你快速发布页面在Github上,使用chmod +x deploy.sh来确保脚本可运行。

下面是脚本deploy.sh的内容:

#!/bin/bash

echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"

# Build the project.
hugo # if using a theme, replace with `hugo -t <YOURTHEME>`

# Go To Public folder
cd public
# Add changes to git.
git add .

# Commit changes.
msg="rebuilding site `date`"
if [ $# -eq 1 ]
  then msg="$1"
fi
git commit -m "$msg"

# Push source and build repos.
git push origin master

# Come Back up to the Project Root
cd ..

你可以执行./deploy.sh "你的commit内容"来将页面更改发布到<USERNAME>.github.io, 注意这里也要将更改commit到步骤1里建立的<YOUR-PROJECT>项目分支中。

大功告成

现在如果你打开https://<USERNAME>.github.io,则会发现你的页面已经成功部署!

本文参考链接

Hugo官方教学:如何将页面部署到Github上