hugo でブログサイト構築

hugo でブログサイト構築

2023/08/15 09:00:00
Program
Wsl, Ubuntu, Go, Hugo

hugo を使って、このblog.oya3.netを作成してみた。
環境は ubuntu22.04 on wsl2 で実施
以下が作成手順

hugo インストール #

# ubuntu22.04 だと 2023/8/14 現在だと v0.92.2 が入るっぽい
$ sudo apt install hugo

apt の場合、リポジトリに登録されているバージョンが古い場合があるので、最新バージョンが必要な場合以下の手順で導入できる
github 更新サイトの以下から最新のdebファイルダウンロードする

2023/8/14 現在だと、hugo_0.117.0_linux-amd64.deb が最新っぽい。 extendedバージョンとして機能追加された hugo_extended_0.117.0_linux-amd64.deb もある

# ここでは extended バージョンをインストールする
$ wget https://github.com/gohugoio/hugo/releases/download/v0.117.0/hugo_0.117.0_linux-amd64.deb
$ sudo dpkg -i hugo_0.117.0_linux-amd64.deb
$ hugo version
hugo v0.117.0-b2f0696cad918fb61420a6aff173eb36662b406e+extended linux/amd64 BuildDate=2023-08-07T12:49:48Z VendorInfo=gohugoio

# dpkg インストールしたものをアンインストールする方法
#  --purge を付けると設定ファイルも削除される
$ sudo dpkg --purge hugo
[sudo] password for developer:
(Reading database ... 99237 files and directories currently installed.)
Removing hugo (0.117.0) ...
dpkg: warning: while removing hugo, directory '/usr/local/bin' not empty so not removed

プロジェクトを作成 #

$ hugo new site blog.oya3.net
$ cd blog.oya3.net
$ git init
$ emacs .gitignore
# Generated files by hugo
public/
resources/_gen/

# Executable may be added to repository
hugo.exe
hugo.darwin
hugo.linux

# Temporary lock file while building
.hugo_build.lock

# Temporary files
.#*
._*
*~

$ git add .
$ git commit -m "first commit"
# 日本語検索を修正するためにサブモジュールにはしない。。。
$ git clone https://github.com/alex-shpak/hugo-book themes/hugo-book
# themes/hugo-book の .git を削除しておく
$ rm -rf themes/hugo-book/.git
$ git add .
$ git commit -m "add hugo-book theme"

# hugo-book theme のサンプルをコピーしておく
$ cp -R themes/hugo-book/exampleSite/content.en/* ./content  
$ cp themes/hugo-book/exampleSite/config.toml .
$ git add .
$ git commit -m "add hugo-book sample"

基本設定を変更 #

$ emacs config.toml

$ git diff  config.toml
diff --git a/config.toml b/config.toml
index 6204c9b..747b6e7 100644
--- a/config.toml
+++ b/config.toml
@@ -1,9 +1,15 @@
 # hugo server --minify --themesDir ../.. --baseURL=http://0.0.0.0:1313/theme/hugo-book/

-baseURL = 'https://example.com/'
-title = 'Hugo Book'
+baseURL = 'https://blog.oya3.net/'
+title = 'blog.oya3.net'
 theme = 'hugo-book'

+# 言語を日本語に設定
+languageCode = "ja"
+defaultContentLanguage = "ja"
+hasCJKLanguage = true
+
+
 # Book configuration
 disablePathToLower = true
 enableGitInfo = true
@@ -16,37 +22,39 @@ enableGitInfo = true
 [markup.tableOfContents]
   startLevel = 1

-# Multi-lingual mode config
-# There are different options to translate files
-# See https://gohugo.io/content-management/multilingual/#translation-by-filename
-# And https://gohugo.io/content-management/multilingual/#translation-by-content-directory
-[languages]
-[languages.en]
-  languageName = 'English'
-  contentDir = 'content.en'
-  weight = 1
-
-[languages.ru]
-  languageName = 'Russian'
-  contentDir = 'content.ru'
-  weight = 2
-
-[languages.zh]
-  languageName = 'Chinese'
-  contentDir = 'content.zh'
-  weight = 3
-
-[menu]
-# [[menu.before]]
-[[menu.after]]
-  name = "Github"
-  url = "https://github.com/alex-shpak/hugo-book"
-  weight = 10
-
-[[menu.after]]
-  name = "Hugo Themes"
-  url = "https://themes.gohugo.io/hugo-book/"
-  weight = 20
+# マルチ言語にはしない
+# # Multi-lingual mode config
+# # There are different options to translate files
+# # See https://gohugo.io/content-management/multilingual/#translation-by-filename
+# # And https://gohugo.io/content-management/multilingual/#translation-by-content-directory
+# [languages]
+# [languages.en]
+#   languageName = 'English'
+#   contentDir = 'content.en'
+#   weight = 1
+
+# [languages.ru]
+#   languageName = 'Russian'
+#   contentDir = 'content.ru'
+#   weight = 2
+
+# [languages.zh]
+#   languageName = 'Chinese'
+#   contentDir = 'content.zh'
+#   weight = 3
+
+# メニューにgitは不要
+# [menu]
+# # [[menu.before]]
+# [[menu.after]]
+#   name = "Github"
+#   url = "https://github.com/alex-shpak/hugo-book"
+#   weight = 10
+
+# [[menu.after]]
+#   name = "Hugo Themes"
+#   url = "https://themes.gohugo.io/hugo-book/"
+#   weight = 20

 [params]
   # (Optional, default light) Sets color theme: light, dark or auto.
@@ -75,9 +83,10 @@ enableGitInfo = true
   # For backward compatibility you can set '*' to render all sections to menu. Acts same as '/'
   BookSection = 'docs'

-  # Set source repository location.
-  # Used for 'Last Modified' and 'Edit this page' links.
-  BookRepo = 'https://github.com/alex-shpak/hugo-book'
+  # github は利用しない
+  # # Set source repository location.
+  # # Used for 'Last Modified' and 'Edit this page' links.
+  # BookRepo = 'https://github.com/alex-shpak/hugo-book'

   # (Optional, default 'commit') Specifies commit portion of the link to the page's last modified
   # commit hash for 'doc' page type.
@@ -86,15 +95,18 @@ enableGitInfo = true
   # Github uses 'commit', Bitbucket uses 'commits'
   # BookCommitPath = 'commit'

-  # Enable "Edit this page" links for 'doc' page type.
-  # Disabled by default. Uncomment to enable. Requires 'BookRepo' param.
-  # Edit path must point to root directory of repo.
-  BookEditPath = 'edit/main/exampleSite'
+  # github は利用しない
+  # # Enable "Edit this page" links for 'doc' page type.
+  # # Disabled by default. Uncomment to enable. Requires 'BookRepo' param.
+  # # Edit path must point to root directory of repo.
+  # BookEditPath = 'edit/main/exampleSite'

   # Configure the date format used on the pages
   # - In git information
   # - In blog posts
-  BookDateFormat = 'January 2, 2006'
+  # BookDateFormat = 'January 2, 2006'
+  # 日本語表記に変更
+  BookDateFormat = "2006/01/02"

   # (Optional, default true) Enables search function with flexsearch,
   # Index is built on fly, therefore it might slowdown your website.

日本語検索のバグを修正 #

$ emacs themes/book/i18n/ja.yaml

$ git diff themes/hugo-book/i18n/ja.yaml
diff --git a/themes/hugo-book/i18n/ja.yaml b/themes/hugo-book/i18n/ja.yaml
index 77f87be..fec0aba 100644
--- a/themes/hugo-book/i18n/ja.yaml
+++ b/themes/hugo-book/i18n/ja.yaml
@@ -10,11 +10,41 @@
 - id: Expand
   translation: 展開

+# https://d3.haro.jp/docs/2021/flexsearch/ に従って修正
+# translation: |
+#   {
+#     encode: false,
+#     tokenize: function(str) {
+#       return str.replace(/[\x00-\x7F]/g, '').split('');
+#     }
+#   }
 - id: bookSearchConfig
   translation: |
     {
       encode: false,
       tokenize: function(str) {
-        return str.replace(/[\x00-\x7F]/g, '').split('');
+        if (!str) return [];
+         const splitedTexts = str
+           // 処理前にアルファベットを小文字に変換
+           .toLowerCase()
+           // 漢字、カナ、半角英数の連続する塊を切り出し
+           // かなと全角英数は対象外
+           .match(/[一-龠]+|[ァ-ヴー]+|[a-z0-9]+/g);
+         if (!splitedTexts) return [];
+         const mappedTexts = splitedTexts
+           .filter((word) => word.length > 1)
+           // 半角英数の場合、前方一致検索ができるように処理
+           .map((word) => {
+             if (word.match(/[a-z0-9]+/g)) {
+               let token = '';
+               return Array.from(word)
+                 .map((char) => (token += char))
+                 .filter((token) => token.length > 1);
+             } else {
+               return word;
+             }
+           });
+         const flatted = mappedTexts.flat();
+         return [...new Set(flatted)];
       }
     }

bookテーマが動作するか確認 #

hugo server -D コマンドを実行する 実行後、以下の通り、http://localhost:1313 にアクセス可能となる。 左ペインの検索で、半角文字で検索が成功していると日本語も正しく検索できるはず。 ※警告はいったん無視しておく。実運用時に必要な内容に絞り込むため。

$ hugo server -D
Start building sites …
hugo v0.92.2+extended linux/amd64 BuildDate=2023-01-31T11:11:57Z VendorInfo=ubuntu:0.92.2-1ubuntu0.1
WARN 2023/08/12 15:25:48 Expand shortcode is deprecated. Use 'details' instead.
WARN 2023/08/12 15:25:48 Page '/overview/configuration/' not found in 'posts/migrate-from-jekyll.md'
WARN 2023/08/12 15:25:48 Page '/layout/templates/' not found in 'posts/migrate-from-jekyll.md'
WARN 2023/08/12 15:25:48 Page '/doc/shortcodes/' not found in 'posts/migrate-from-jekyll.md'
WARN 2023/08/12 15:25:48 Page '/layout/variables' not found in 'posts/goisforlovers.md'
WARN 2023/08/12 15:25:48 Page '/layout/functions' not found in 'posts/goisforlovers.md'
WARN 2023/08/12 15:25:48 Page '/content/front-matter' not found in 'posts/goisforlovers.md'

                   | JA
-------------------+-----
  Pages            | 57
  Paginator pages  |  0
  Non-page files   |  0
  Static files     | 78
  Processed images |  0
  Aliases          | 11
  Sitemaps         |  1
  Cleaned          |  0

Built in 106 ms
Watching for changes in /home/developer/work/blog.oya3.net/{archetypes,content,data,layouts,static,themes}
Watching for config changes in /home/developer/work/blog.oya3.net/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
^C

# 期待通り動作したら git commit する
$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   config.toml
        modified:   themes/hugo-book/i18n/ja.yaml

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        .hugo_build.lock
        resources/
$ git add .
$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   .hugo_build.lock
        modified:   config.toml
        new file:   resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.content
        new file:   resources/_gen/assets/scss/book.scss_50fc8c04e12a2f59027287995557ceff.json
        modified:   themes/hugo-book/i18n/ja.yaml
$ git commit -m "add my init settings"

apache用virtualhostファイルを準備 #

アプリカレントディレクトリに apache.confs ディレクトリを作成し、blog.oya3.net.conf を設置しておく。

$ mkdir apache.confs $ emacs blog.oya3.net.conf

blog.oya3.net.conf は以下の内容

<VirtualHost *:80>
    ServerName blog.oya3.net
    DocumentRoot /home/[user]/blog.oya3.net/public
    <Directory "/home/[user]/blog.oya3.net">
        Options Includes ExecCGI FollowSymLinks
        AllowOverride All
        Order allow,deny
        Allow from all
        Require all granted
    </Directory>
</VirtualHost>

ディレクトリ階層は以下の通り

$ tree --gitignore -L 2
.
├── apache.confs
│   └── blog.oya3.net.conf
├── archetypes
│   └── default.md
├── config.toml
├── content
│   ├── _index.md
│   ├── docs
│   ├── menu
│   └── posts
├── data
├── layouts
├── resources
│   └── _gen
├── static
└── themes
    └── hugo-book

その他、独自設定 #

記載中。。。

参考URL #