使用Hugo搭建靜態個人站點

Hugo是一款由 GO 語言實現的靜態網站生成器。簡單、易用、高效、易擴展、快速部署。

安裝

Mac 下的安裝

$ brew install hugo
$ hugo version // 是否安裝成功
$ hugo --help

生成 Blog

創建網站

$ hugo new site vicky335.github.io

目錄結構

hugo 生成的博客的基本目錄如下

  • archetypes - 預定義看板,在這類,你可以定制你生成的博客的基本模板。
  • content - 網站的所有內容都保存在這裡
  • data - 保存站點可使用的配置文件
  • layouts - 自定義的模板
  • public - 生成的可直接部署的博客
  • static - 靜態文件,比如你站點需要用到的 logo、頭像等

目錄的話,其實用到的地方不多,一般人只需要按照默認的主題來就行。

安裝主題

安裝主題

生成網站之後,首先要做的就是下載主題,通常有兩種方法。

第一種是下載所有主題,簡單粗暴


$ cd vicky335.github.io
$ git clone --depth 1 --recursive https://github.com/gohugoio/hugoThemes.git themes

第二種是下載感興趣的主題(以 Casper 為例)


$ git clone https://github.com/vjeantet/hugo-theme-casper themes/casper

你也可以選其他主題,進到該主題的 GitHub repo,將上面的網址改成 repo 的網址、themes/casper 改成 themes/你的主題名稱。

使用主題

config.toml 中配置 theme = “casper” 即可。

編輯 config.toml

使用文字編輯器打開 config.toml,並調整內容。

baseURL = "https://vicky335.github.io/"    #改成你的GitHub帳號名稱
languageCode = "zh-cn"
title = "Vicky Blog"    #自由命名

創建文章

首先,生成第一篇文章。


$ hugo new post/first.md

生成的文章內容如下:


+++
title: "First"
date: 2017-04-12T21:57:04+08:00
draft: true
+++

該文章的默認模板是根據 archetypes 目錄下的 default.md 來的,可以自己修改模板,比如,修改文章的時間格式


+++
title: "{{ replace .Name "-" " " | title }}"
date: {{ now.Format "2006-01-01"  }}
draft: false
categories: []
tags: []
toc: false
+++

再次生成文章


$ hugo new post/second.md

生成的文章內容變成了


+++
title: "Second"
date: 2017-04-12
draft: false
categories: []
tags: []
toc: false
+++

生成最終網站

生成靜態博客並在本地查看


$ hugo server

執行完後,在瀏覽器中輸入網址 http://localhost:1313,就可以看到網站的雛形。

默認的話,只會顯示 draftfalse 的文章。

服務器是實時更新的,只要你的內容發生了變化,本地服務器會實時更新變化後的內容,也可以設置成不實時更新


$ hugo server --watch=false

hugo server 並不會生成真正的站點,一般在部署之前,需要運行 hugo 命令生成 public 站點

$ hugo

部署到 GitHub

Hugo 部署在 GitHub 的方式有兩種,這邊介紹部署個人唯一主頁的方式。

在 GitHub 建立 repo

在 GitHub 建立 vicky335.github.io (粗斜體處改成自己的帳號名稱) repo。

將 /public 資料夾連結到 GitHub 上的 vicky335.github.io


cd public
git init
git remote add origin https://github.com/vicky335/vicky335.github.io.git
git add .
git commit -m "Initial commit"
git push -u origin master

等個幾分鐘,輸入網址 https://vicky335.github.io/ 就大功告成囉!