使用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上_第1张图片

当然不想用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:
  config      Print the site configuration
  convert     Convert your content to different formats
  deploy      Deploy your site to a Cloud provider.
  env         Print Hugo version and environment info
  gen         A collection of several useful generators.
  help        Help about any command
  import      Import your site from others.
  list        Listing out various types of content
  mod         Various Hugo Modules helpers.
  new         Create new content for your site
  server      A high performance webserver
  version     Print the version number of Hugo

Flags:
  -b, --baseURL string             hostname (and path) to the root, e.g. http://spf13.com/
  -D, --buildDrafts                include content marked as draft
  -E, --buildExpired               include expired content
  -F, --buildFuture                include content with publishdate in the future
      --cacheDir string            filesystem path to cache directory. Defaults: $TMPDIR/hugo_cache/
      --cleanDestinationDir        remove files from destination not found in static directories
      --config string              config file (default is path/config.yaml|json|toml)
      --configDir string           config dir (default "config")
  -c, --contentDir string          filesystem path to content directory
      --debug                      debug output
  -d, --destination string         filesystem path to write files to
      --disableKinds strings       disable different kind of pages (home, RSS etc.)
      --enableGitInfo              add Git revision, date and author info to the pages
  -e, --environment string         build environment
      --forceSyncStatic            copy all files when static is changed.
      --gc                         enable to run some cleanup tasks (remove unused cache files) after the build
  -h, --help                       help for hugo
      --i18n-warnings              print missing translations
      --ignoreCache                ignores the cache directory
      --ignoreVendor               ignores any _vendor directory
      --ignoreVendorPaths string   ignores any _vendor for module paths matching the given Glob pattern
  -l, --layoutDir string           filesystem path to layout directory
      --log                        enable Logging
      --logFile string             log File path (if set, logging enabled automatically)
      --minify                     minify any supported output format (HTML, XML etc.)
      --noChmod                    don't sync permission mode of files
      --noTimes                    don't sync modification time of files
      --path-warnings              print warnings on duplicate target paths etc.
      --poll string                set this to a poll interval, e.g --poll 700ms, to use a poll based approach to watch for file system changes
      --print-mem                  print memory usage to screen at intervals
      --quiet                      build in quiet mode
      --renderToMemory             render to memory (only useful for benchmark testing)
  -s, --source string              filesystem path to read files relative from
      --templateMetrics            display metrics about template executions
      --templateMetricsHints       calculate some improvement hints when combined with --templateMetrics
  -t, --theme strings              themes to use (located in /themes/THEMENAME/)
      --themesDir string           filesystem path to themes directory
      --trace file                 write trace to file (not useful in general)
  -v, --verbose                    verbose output
      --verboseLog                 verbose logging
  -w, --watch                      watch filesystem for changes and recreate as needed

Additional help topics:
  hugo check   Contains some verification checks

Use "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是网站的标题,就像这个
image-20210808110424578.png

现在可以使用以下命令运行以下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          |  0

Built 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上_第2张图片

在网页下方的说明内,找到主题安装的方法

或者,直接去主题的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上_第3张图片

直接去掉就好了,反正国内也用不到这些

在执行一次命令

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

提示以下,commit -m 后面的东西是此次提交的备注,通常用来说明提交人的名字

你可能感兴趣的:(使用hugo生成静态博客并部署在GitHub上)