如题,本文分成三个部分来撰写。以下全文基于 Ubuntu 18.05 编写。

一、安装

因为 hugo 依赖于 golang,因此,在安装 hugo 之前,先要安装 golang。以下是安装 golang 的步骤。

  1. 官网下载对应的 go 版本。
  2. 删除电脑中以前的版本以及将第一步下载的 tar 包解压出来。放到/usr/local/路径下。(请注意tar包的文件名)
1
$ rm -rf /usr/local/go && tar -C /usr/local -xzf go1.19.linux-amd64.tar.gz
  1. /usr/local/go/bin添加到系统路径下。
1
$ export PATH=$PATH:/usr/local/go/bin
  1. 检查是否安装成功。
1
2
$ go version
go version go1.19 linux/amd64

至此,我们可以从源码来安装我们的 hugo了。

1
2
3
4
5
$ mkdir $HOME/src
$ cd $HOME/src
$ git clone https://github.com/gohugoio/hugo.git
$ cd hugo
$ go install --tags extended

如果你不需要 Sass/SCSS 支持,在上面第五步时将--tags extended移除即可。这样你可以获取到一个更加轻便的 hugo 执行文件。

注意:在执行go install时,受网络环境因素影响,会因为下载不到编译时所需模块而导致安装失败。这时候我们只能将模块库换回国内的代理了。

1
2
$ go env -w GO111MODULE=on
$ go env -w GOPROXY=https://goproxy.cn,direct
  1. go install 指令会将 hugo 安装在GOPATH所指定的bin目录下。想要知道GOPATH的值,用以下指令:
1
2
3
4
5
6
$ go env
GOPATH="/home/chenshiyi/go"
$ chenshiyi@chenshiyi:~/go/bin$ ls
hugo
$ chenshiyi@chenshiyi:~/go/bin$ pwd
/home/chenshiyi/go/bin

/home/chenshiyi/go添加到系统环境中即可。

二、使用

在开始使用 hugo 之前,我们先要初始化一个文件夹。博客的相关配置文件、主题以及你写的文章全部都在这个文件夹内。也就是说:文件夹=网站。换一句话说,如果将来需要备份网站,直接保存这个文件夹即可。下面是步骤:

  1. 初始化文件夹。文件夹的名称由自己定义。在本文中文件夹名称为demosite
1
$ hugo new site demosite
  1. 添加一个主题,并且在config.toml中指定该主题。
1
2
3
4
$ cd demosite
$ git init
$ git submodule add https://github.com/theNewDynamic/gohugo-theme-ananke.git themes/ananke
$ echo theme = \"ananke\" >> config.toml
  1. 添加文章
1
hugo new posts/my-first-post.md

注意:打开my-first-post.md后,draft:true意思是这篇文章的属性为草稿。我们要将它改为非草稿:draft:false。此后将你要写的内容卸载文件内即可。

  1. 开启 hugo server。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
$ hugo server -D

                   | EN
+------------------+----+
  Pages            | 10
  Paginator pages  |  0
  Non-page files   |  0
  Static files     |  3
  Processed images |  0
  Aliases          |  1
  Sitemaps         |  1
  Cleaned          |  0

Total in 11 ms
Watching for changes in /Users/bep/quickstart/{content,data,layouts,static,themes}
Watching for config changes in /Users/bep/quickstart/config.toml
Environment: "development"
Serving pages from memory
Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop

此时 hugo 会在你的本地开启一个网站服务器,点击http://localhost:1313/就可以在浏览器上看到你的网站了。由于当前的网站只是在你的电脑上,别人是看不见的,如果希望别人看得见,我们需要将我们的网站发布在公网上。比如:发表在github上

三、恢复

其实恢复的本质就是将上面说的文件夹恢复到本地。具体的方法各有不同。唯一需要注意的是,因为我们安装主题时,是以 submodule 的形式安装的,因此我们恢复主题稍有麻烦。具体命令如下。

1
$ git submodule update --init

更为详细的教程,请看Using submodules in Git - Tutorial