Hugo を使ってブログを開設してみる


2021/10/10

Takuji Sano


Hugo を使ってブログを開設してみる

はじめに

Github のアカウントを作成して早数年…
当時 jekyll を使って、Github Pages に自分のサイトを作成してから放置状態でした。
最近アクティブに使うようになり、イロイロと調べていると、みなさんプロフィール画面の README をカスタマイズされています。海外のエンジニアは熱心にカスタムしてる印象です。
おそらく名刺代わりになるツールなんでしょう。たぶん。
ということで、私もカスタマイズしてみました。
そうすると、気になるのは放置状態のサイト…
これは、刷新しなければと思い立ったのがきっかけです。
ググってみると jekyll か Hugo か pelican を使われてる方が多そうです。
Hugo のテーマが豊富だったので、今回は Hugo に乗り換えてみようと思います。

下記のページを参考にしながら、やってみました。
https://open-groove.net/other-tools/hugo-github-pages-blog/
https://yonehub.y10e.com/2019/10/22/20191022_hugo_githubio/

hugo のインストール

下記コマンドでインストールして、バージョン確認します。

$ brew install hugo
$ brew version
hugo v0.88.1+extended darwin/amd64 BuildDate=unknown

次にワークディレクトリを作成します。

$ hugo new site blog

Theme のインストール

hugo で準備されているテーマを下記のサイトで選びます。
https://themes.gohugo.io/

今回は「Tella」というテーマで作業を進めてみます。
https://github.com/opera7133/tella

download を押すと、そのテーマのリポジトリに飛びます。
見てみると、postcss-cli と autoprefixer がインストールされていることが前提条件のようです。
これをインストールするための npm コマンドが必要そうです。
これは、node.js をインストールすると同時にインストールされるという情報がありました。
まずは、node.js がインストールされているか確認しましょう。

$ node -v

インストールされていない場合は、node.js の管理を行うための nodebrew が必要みたいです。

$ brew install nodebrew

問題なくインストールされたら、バージョン確認すると、以下のように表示されます。

$ nodebrew -v
nodebrew 1.1.0

Usage:
    nodebrew help                         Show this message
    nodebrew install <version>            Download and install <version> (from binary)
    nodebrew compile <version>            Download and install <version> (from source)
    nodebrew install-binary <version>     Alias of `install` (For backward compatibility)
    nodebrew uninstall <version>          Uninstall <version>
    nodebrew use <version>                Use <version>
    nodebrew list                         List installed versions
    nodebrew ls                           Alias for `list`
    nodebrew ls-remote                    List remote versions
    nodebrew ls-all                       List remote and installed versions
    nodebrew alias <key> <value>          Set alias
    nodebrew unalias <key>                Remove alias
    nodebrew clean <version> | all        Remove source file
    nodebrew selfupdate                   Update nodebrew
    nodebrew migrate-package <version>    Install global NPM packages contained in <version> to current version
    nodebrew exec <version> -- <command>  Execute <command> using specified <version>

Example:
    # install
    nodebrew install v8.9.4

    # use a specific version number
    nodebrew use v8.9.4

管理ツールがインストールできたので、このツールで node.js の最新版をインストールします。

$ nodebrew install-binary latest

なんかエラーが出ました。

Fetching: https://nodejs.org/dist/v16.11.0/node-v16.11.0-darwin-x64.tar.gz
Warning: Failed to create the file
Warning: .nodebrew/src/v16.11.0/node-v16.11.0-darwin-x64.tar.gz:
Warning: No such file or directory

ディレクトリが無いからかファイルが作れない?

$ mkdir ~/.nodebrew/src/
$ nodebrew install-binary latest
Fetching: https://nodejs.org/dist/v16.11.0/node-v16.11.0-darwin-x64.tar.gz
############################################################################################################################################################################################# 100.0%
Installed successfully

うまくいきました。
インストールされているバージョンを確認しておきましょう。

$ nodebrew list
v16.11.0

current: none

ここで、「current: none」と表示されているのは、有効になっていないからだそうです。
下記コマンドで有効にして、バージョンを再確認しておきます。

$ nodebrew use v16.11.0
use v16.11.0
$ nodebrew list
v16.11.0

current: v16.11.0

最後にパスを通しておく必要があるみたいです。

$ echo 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.zshenv
$ source ~/.zshenv

これで、node.js のバージョン確認ができます。

$ node -v
v16.11.0

当初の目的の npm のバージョン確認もしておきましょう。

$ npm -v
8.0.0

やっと、Theme のインストールに戻れます。

$ npm install -g postcss-cli

added 74 packages, and audited 75 packages in 10s

12 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

$ npm install -g autoprefixer

added 13 packages, and audited 14 packages in 2s

5 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

README に書かれている、Method1 の方法で試してみます。

$ git https://github.com/opera7133/tella.git themes/tella

クローンできたら、インストールします。

$ cd themes/tella/
$ npm install
npm WARN old lockfile
npm WARN old lockfile The package-lock.json file was created with an old version of npm,
npm WARN old lockfile so supplemental metadata must be fetched from the registry.
npm WARN old lockfile
npm WARN old lockfile This is a one-time fix-up, please be patient...
npm WARN old lockfile

added 199 packages, and audited 200 packages in 17s

27 packages are looking for funding
  run `npm fund` for details

1 moderate severity vulnerability

To address all issues, run:
  npm audit fix

Run `npm audit` for details.

なにやら、脆弱性が疑われるライブラリバージョンが使われているワーニングのようですので、次のコマンドで解決を図ります。

$ npm audit fix

changed 1 package, and audited 200 packages in 3s

27 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

「found 0 vulnerabilities」(脆弱性が 0 件発見された)ということで、解決できたようです。
次に設定ファイルを編集します。

$ cp ../../
$ vi config.toml

URL、適用するテーマなどを設定します。
編集後は下記のようになります。

baseURL = 'http://takuji-sano.github.io/'
languageCode = 'ja-jp'
title = 'My New Hugo Site'
theme = 'Tella'

次にトップページを作成します。
Theme の exampleSite からコピーして編集します。

$ cp themes/tella/exampleSite/content/_index.md content
$ vi content/_index.md

編集後は下記のようにしました。

+++
author = "Takuji Sano"
+++

動作確認用の記事を作成します。

$ hugo new post/20211010-1_init-post.md
〜略〜/blog/content/post/20211010-1_init-post.md created

/content/post/20211010-1_init-post.md というファイルが生成されるので、これを編集します。

---
title: "20211010 1_init Post"
date: 2021-10-10T10:25:28+09:00
categories: [ Uncategorized ]
tags: [ blog ]
draft: true
---

Github Pages と hugo を使ったブログ環境の動作確認用の記事です。

こんな感じで、動作確認してみます。

$ hugo server
Start building sites …
hugo v0.88.1+extended darwin/amd64 BuildDate=unknown

                   | EN
-------------------+-----
  Pages            |  6
  Paginator pages  |  0
  Non-page files   |  0
  Static files     | 29
  Processed images |  0
  Aliases          |  2
  Sitemaps         |  1
  Cleaned          |  0

Built in 10630 ms
Watching for changes in blog/{archetypes,content,data,layouts,static,themes}
Watching for config changes in blog/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」にアクセスし、何か表示されていれば、ひとまず動作はしています。
ですが、準備した記事が表示されません…
何かが違うようです。

theme の exampleSite にある config.toml をコピーしてやってみましょう。

$ cp themes/tella/exampleSite/config.toml ./
$ vi config.toml

最初のメタデータ部分を以下のように編集しました。

  1 baseURL = "https://takuji-sano.github.io"↲
  2 title = "Tella"↲
  3 author = "Takuji Sano"↲
  4 languageCode = "ja-jp"↲
  5 DefaultContentLanguage = "ja"↲
  6 enableInlineShortcodes = true↲
  7 theme = "tella"↲
  8 enableRobotsTXT = true↲
  9 ↲
 10 # Please enable this feature if the site is available in Japanese, Chinese or Korean.↲
 11 hasCJKLanguage = true↲
 12 ↲
 13 # If you're using Google Analytics, you can enable this feature.↲
 14 googleAnalytics = "UA-12345678-1"↲

サーバを起動させて、再確認すると、メニューなどが表示されました。
サーバ起動時にテーマを指定することができるようですので、試してみましょう。

$ hugo server -D -t Tella

準備した記事が表示されました。
config.toml にテーマ名を記述したのに… なんででしょうね。
ま、おいといて。
少し、勘違いしていましたが、Theme を設定するとデモにあったようなサイトができると思っていました。
とりあえず、デモと同じ状態にするために themes/tella/exampleSite にあるコンテンツを themes/tella/ 以下のディレクトリにコピーしてみます。

$ cp exampleSite/archetypes/* archetypes
$ cp -r exampleSite/static/img/ static/img
$ cp exampleSite/content/about.md ../../content
$ cp exampleSite/content/contact.md ../../content
$ cp -r exampleSite/content/blog ../../content/
$ cp -r exampleSite/content/products ../../content/
$ cp -r exampleSite/data ./

はい。ようやくできました。
ですが、動作確認用の記事が見えなくなりました。
Theme の構造からすると、post ではなく blog に記事を作成するみたい。

$ hugo new blog/20211010-1_init-post.md

できた〜。
post は消しておきましょう。

rm -rf content/post/

Theme のその他ページや表示されるテキストなどの細かな部分は、おいおい直すとして。
次に進めましょう。

Github Pages 公開用の設定

ここで、[github ユーザ名].github.io という名前のリポジトリを Public で作成しておいてください。
下記のコマンドで初期化します。

$ echo "# takuji-sano.github.io" >> README.md
$ git init
$ git add README.md
$ git commit -m "first commit"
$ git branch -M main
$ git remote add origin https://github.com/takuji-sano/takuji-sano.github.io.git
$ git push -u origin main

https://takuji-sano.github.io/ にアクセスしてページが表示されたら問題ありません。

で、参考にしているページは共に、public ディレクトリをリポジトリにプッシュする的な話になるが、どこにも public なんで無い…
よーわからんので、イロイロ漁ってみると、https://qiita.com/BIwashi/items/c011454bdb9a523bba4aに説明がありました!
次のコマンド実行で public ができるみたい。

$ hugo

できたー!
ようやく意味わかってきた。hugo コマンドで書いた記事をコンパイルして public ディレクトリに静的サイトが生成されるのね。
で、それを github.io のリポジトリのサブモジュールとして紐付けておけば良いと。

ようやく公開環境のできあがりかと思ったら…
github pages の仕様で、公開ディレクトリは「docs」だそうで…
その設定が必要です。
config.toml に下記の1行を追記して、hugo コマンドで生成します。
また、先程の public は不要ですので削除しておきます。

$ vi config.toml
追記する記述:publishDir = "docs"
$ rm -rf public/
$ hugo

次に、リポジトリにアクセスして、[Settings] の左メニューにある [Pages] の source にある /(root) を /docs に変更して、save ボタンを押します。
最後に、生成した docs を github.io/docs のサブモジュールとしておけば良さそうです。
が… イロイロとやってみましたが、うまく行かず…
最終的には、config.toml の publishDir を “../takuji-sano.github.io/docs” としたら一応できた。
けど、よく見ると追加した記事だけ表示されない…
ローカルのサーバで表示させると問題ないが、github.io にアップすると表示されない。

で、結局は、追加した記事のメタデータにある draft が true だったので、非公開扱いされてただけでした…

draft: false

ふぅ。やっとできた。 全体の流れを書いておきます。

  • 記事の雛形を生成する
    $ hugo new blog/xxx
  • 記事を書く
  • ローカルサーバで内容を確認する
    $ hugo server -D -t tella
  • 問題なければ、draft: false としてデプロイ
    $ hugo
  • github.io の変更をコミット&プッシュ