使用hugo生成静态博客并部署在GitHub上

简介 hugo是一个用Go语言编写的静态网页生成器,只需要一个命令 hugo 就可以在几秒钟内生成一个静态的博客页面,被称为世界上最快的网站构建框架,使hugo称为最受欢迎且最热门的静态网站生成器之一。
我之前使用的是wordpress作为博客的载体,但是wordpress太笨重,对markdown格式的支持不是很好,且打开速度极慢,所以就使用hugo进行博客的撰写,生成静态博客后就可以部署在云服务器上或者GitHub上,这样在国内搜到的云服务器上的博客http://www.mockingj.cn,在国外就是github上的pageshttps://caecarxu.github.io/,这样国内外都有一个比较好的访问速度。
1、安装hugo
我使用的系统是windows10,在hugo的官方文档中,使用Scoop作为包管理器,用一个命令行就完成下载

scoop install hugo

或者是安装hugo的extend版本
scoop install hugo-extended

安装成功后验证一下,在命令行中输入
hugo version

若输出
hugo v0.86.1-F6821B88 windows/amd64 BuildDate=2021-07-30T10:13:35Z VendorInfo=gohugoio

则为成功安装
使用hugo生成静态博客并部署在GitHub上
文章图片

当然不想用windows的包管理器,可以使用git进行下载
git clone https://github.com/gohugoio/hugo.git#将hugo下载至命令行所在文件夹

然后在右击windows中的此电脑,在选择框中选择属性->高级系统设置->环境变量->系统变量->Path->编辑,将刚刚的hugo文件夹加入Path中
重启电脑,执行hugo version命令,验证安装。
2、使用hugo
在命令行中执行hugo help可以查看hugo的基本使用方法:
hugo is the main command, used to build your Hugo site.Hugo is a Fast and Flexible Static Site Generator built with love by spf13 and friends in Go.Complete documentation is available at http://gohugo.io/.Usage: hugo [flags] hugo [command]Available Commands: configPrint the site configuration convertConvert your content to different formats deployDeploy your site to a Cloud provider. envPrint Hugo version and environment info genA collection of several useful generators. helpHelp about any command importImport your site from others. listListing out various types of content modVarious Hugo Modules helpers. newCreate new content for your site serverA high performance webserver versionPrint the version number of HugoFlags: -b, --baseURL stringhostname (and path) to the root, e.g. http://spf13.com/ -D, --buildDraftsinclude content marked as draft -E, --buildExpiredinclude expired content -F, --buildFutureinclude content with publishdate in the future --cacheDir stringfilesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/ --cleanDestinationDirremove files from destination not found in static directories --config stringconfig file (default is path/config.yaml|json|toml) --configDir stringconfig dir (default "config") -c, --contentDir stringfilesystem path to content directory --debugdebug output -d, --destination stringfilesystem path to write files to --disableKinds stringsdisable different kind of pages (home, RSS etc.) --enableGitInfoadd Git revision, date and author info to the pages -e, --environment stringbuild environment --forceSyncStaticcopy all files when static is changed. --gcenable to run some cleanup tasks (remove unused cache files) after the build -h, --helphelp for hugo --i18n-warningsprint missing translations --ignoreCacheignores the cache directory --ignoreVendorignores any _vendor directory --ignoreVendorPaths stringignores any _vendor for module paths matching the given Glob pattern -l, --layoutDir stringfilesystem path to layout directory --logenable Logging --logFile stringlog File path (if set, logging enabled automatically) --minifyminify any supported output format (HTML, XML etc.) --noChmoddon't sync permission mode of files --noTimesdon't sync modification time of files --path-warningsprint warnings on duplicate target paths etc. --poll stringset this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes --print-memprint memory usage to screen at intervals --quietbuild in quiet mode --renderToMemoryrender to memory (only useful for benchmark testing) -s, --source stringfilesystem path to read files relative from --templateMetricsdisplay metrics about template executions --templateMetricsHintscalculate some improvement hints when combined with --templateMetrics -t, --theme stringsthemes to use (located in /themes/THEMENAME/) --themesDir stringfilesystem path to themes directory --trace filewrite trace to file (not useful in general) -v, --verboseverbose output --verboseLogverbose logging -w, --watchwatch filesystem for changes and recreate as neededAdditional help topics: hugo checkContains some verification checksUse "hugo [command] --help" for more information about a command.

这里我们只需要使用几个命令就可以了:
建立博客,名为test
hugo new site test

输出
Congratulations! Your new Hugo site is created in C:\git\hugo_blog\test.Just a few more steps and you're ready to go:1. Download a theme into the same-named folder. Choose a theme from https://themes.gohugo.io/ or create your own with the "hugo new theme " command. 2. Perhaps you want to add some content. You can add single files with "hugo new \.". 3. Start the built-in live server via "hugo server".Visit https://gohugo.io/ for quickstart guide and full documentation.

这样就生成了一个博客,相关的文件都在test文件夹内
进入博客文件夹内
cd test

test文件夹内会有一个config.toml的文件,这个文件是hugo的配置文件
baseURL = "http://example.org/" languageCode = "en-us" title = "My New Hugo Site"

baseURL是博客的网址,生成的博客资源都是基于这个网址进行获取的
title是网站的标题,就像这个
使用hugo生成静态博客并部署在GitHub上
文章图片

现在可以使用以下命令运行以下hugo博客的预览
hugo server

输出
Start building sites … hugo v0.86.1-F6821B88 windows/amd64 BuildDate=2021-07-30T10:13:35Z VendorInfo=gohugoio WARN 2021/08/08 11:08:08 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2021/08/08 11:08:08 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination. WARN 2021/08/08 11:08:08 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.| EN -------------------+----- Pages|3 Paginator pages|0 Non-page files|0 Static files|0 Processed images |0 Aliases|0 Sitemaps|1 Cleaned|0Built in 37 ms Watching for changes in C:\git\hugo_blog\test\{archetypes,content,data,layouts,static} Watching for config changes in C:\git\hugo_blog\test\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

倒数第二行显示了博客的地址localhost:1313,若1313地址被使用,则会随机使用一个端口
但是现在的博客还什么都没有,打开就是一片空白
所以现在需要加入主题设计
3、加入主题并运行博客
在网上查询之后,发现HUGO官方搭建的theme主题站,大量的开源主题可供选择。
基本上所有的主题都自带安装的方法
这里我选择了一个主题进行调试https://themes.gohugo.io/them...
使用hugo生成静态博客并部署在GitHub上
文章图片

在网页下方的说明内,找到主题安装的方法
或者,直接去主题的github网址,里面的readme.md中有说明主题的下载和使用方式,两个方法都是一样的
于是,根据主题作者提供的命令
git clone https://github.com/apvarun/blist-hugo-theme.git themes/blist##获得主题

下载完成后,将 package.json 文件从 themes/showcase 文件夹复制到你的 Hugo 网站根文件夹,然后运行 npm install
进入themes/blist/exampleSite文件夹中,复制exampleSite中的文件,替换掉Hugo网站根文件夹中的相同命名的文件
执行命令
hugo serve

这个时候有可能会因为一些twitter或者facebook的api无法访问而导致的问题
Start building sites … hugo v0.86.1-F6821B88 windows/amd64 BuildDate=2021-07-30T10:13:35Z VendorInfo=gohugoio ERROR 2021/08/08 15:05:14 Failed to get JSON resource "https://api.twitter.com/1/statuses/oembed.json?id=1085870671291310081&omit_script=true": Get "https://api.twitter.com/1/statuses/oembed.json?id=1085870671291310081&omit_script=true": dial tcp 162.125.2.6:443: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. If you feel that this should not be logged as an ERROR, you can ignore it by adding this to your site config: ignoreErrors = ["error-remote-getjson"] Error: Error building site: "C:\git\hugo_blog\test\content\blog\rich-content.md:1:1": timed out initializing value. You may have a circular loop in a shortcode, or your site may have resources that take longer to build than the `timeout` limit in your Hugo config file. Built in 37375 ms

这个时候就去寻找报错中使用这些资源的文件
使用hugo生成静态博客并部署在GitHub上
文章图片

直接去掉就好了,反正国内也用不到这些
在执行一次命令
hugo serve

成功运行博客!!!
4、将博客部署到github上
这部分需要使用到一个叫做github page的东西,是GitHub提供的一个网页寄存服务,可以寄存静态页面,这个特性就特别适合博客的搭建。
首先再Github上创建一个 Repository,命名为Github名字.github.io,譬如我的仓库caecarxu.github.io,这样就可以生成一个用户页面
在hugo server调式页面完成后,使用命令hugo生成hugo静态页面。
注意!!!在生成静态页面之前要把config.toml文件中的baseURL修改为自己博客的网址,譬如
baseURL = "https://caecarxu.github.io/"

hugo##生成静态页面文件

在命令执行后,出现一个public文件夹,里面就是网站的静态页面文件
进入public文件夹,使用git上传文件
cd public git init##初始化仓库 git remote add origin https://github.com/caecarxu/caecarxu.github.io.git##链接远程仓库 git add . git commit -m "first commit" git push -u origin master

在此之后更新文章,使用hugo生成新的静态页面,并使用git push进行同步
cd public git add . git status git commit -m "add blog post" git push

【使用hugo生成静态博客并部署在GitHub上】提示以下,commit -m 后面的东西是此次提交的备注,通常用来说明提交人的名字

    推荐阅读