乐趣区

关于hugo:使用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

则为胜利装置

当然不想用 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 <THEMENAME>" command.
2. Perhaps you want to add some content. You can add single files
   with "hugo new <SECTIONNAME>\<FILENAME>.<FORMAT>".
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 博客的预览

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…

在网页下方的阐明内,找到主题装置的办法

或者,间接去主题的 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 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 前面的货色是此次提交的备注,通常用来阐明提交人的名字

退出移动版