Hugoのテーマをモジュールとして利用したい。
これまでは、本サイトではGitHubで開発している自作のHugoテーマをコンポーネントとして利用してきた。1
コンポーネント方式のテーマ導入に必要なことは以下になる。
サイト側 | テーマ側 |
---|---|
git submodule add URL でテーマをダウンロード |
なし |
hugo.tomlのtheme にテーマ名を設定 |
HugoにはHugo Modulesという方式もあるため、そちらに移行したい。
解決策
Hugo ModulesはGo言語のModule機能を利用しているため、予めThe Go Programming Languageのインストールが必要になる。
移行方法
今回のモジュール方式でテーマ導入に必要なことは以下になる。
サイト側 | テーマ側 |
---|---|
hugo mod init でモジュール化 |
hugo mod init でモジュール化 |
hugo.tomlのmodule.imports でテーマをインポート |
|
必要に応じて、hugo.tomlのmodule.mounts でマウント |
具体的な手順は以下となる。
手順1. テーマ側をHugoモジュール化
GitHubで管理している自作テーマをクローンする。
git clone https://github.com/kantas-spike/kantas-theme.git
cd kantas-theme
以下のコマンドを実行し、Hugoモジュール化する。
hogo mod init
の後には、github.com/<your_user>/<your_project>
を指定する必要がある。
hugo mod init github.com/kantas-spike/kantas-theme
go.mod
というファイルが追加されるので、コミットし、GitHubにプッシュする。
手順2. サイト側をHugoモジュール化
Hugoのモジュールを利用するためには、サイト側もモジュール化する必要がある。
以下のコマンドを実行し、モジュール化する。
サイトの場合、他のモジュールから利用されることはないため、
hogo mod init
の後には、適当な名前を付ける。今回はmyblog
を指定した。2
cd myblog
hugo mod init myblog
手順3. サイト側のhugo.tomlを変更
-
まず。
hugo.toml
のtheme
設定を削除する。# ...略... # 実際は以下の設定をコメントアウトではなく削除する # theme = 'kantas' # ...略...
-
hugo.toml
でテーマをインポート以下を追加し、テーマをモジュールとしてインポートする。
# ...略... [module] [[module.imports]] path = 'github.com/kantas-spike/kantas-theme' # ...略...
-
hugo.toml
に必要なファイルをマウントする本ブログでは、
tailwindcss
を採用している。tailwindcss
の不要CSSクラスの削除用に、Hugoのhugo_stats.json
を利用している。3hugo_stats.json
を生成・監視用の設定として以下を追加している。# テーマで使用するtailwindcss用の設定 [build] writeStats = true [[build.cachebusters]] source = "assets/watching/hugo_stats\\.json" target = "theme\\.css" [[build.cachebusters]] source = "assets/js/.*\\.js" target = "theme\\.css"
この監視用の
[[build.cachebusters]]
設定では、source
にマウントされた仮想ファイルシステム上のパスを指定する必要がある。 そのため、以下のmount
設定も追加している。# ...略... [module] # (A)のみ設定すると、 # デフォルト設定の"assets"のマウントが外れるため明示的に設定 [[module.mounts]] source = "assets" target = "assets" [[module.mounts]] # (A) source = "hugo_stats.json" target = "assets/watching/hugo_stats.json" # ...略...
まとめると、
[module]
と[build]
でhugo.toml
に以下の設定をしている。# ...略... [module] # テーマで使用するアセットの登録 [[module.mounts]] source = "assets" target = "assets" [[module.mounts]] source = "hugo_stats.json" target = "assets/watching/hugo_stats.json" # テーマのインポート [[module.imports]] path = 'github.com/kantas-spike/kantas-theme' # テーマで使用するtailwindcss用の設定 [build] writeStats = true [[build.cachebusters]] source = "assets/watching/hugo_stats\\.json" target = "theme\\.css" [[build.cachebusters]] source = "assets/js/.\*\\.js" target = "theme\\.css" # ...略...
-
最後に、テーマ側に必要なパッケージをサイト側にインストールする
以下を実行して、テーマで利用しているパッケージをサイト側で収集する。
hugo mod npm pack
package.json
に、テーマに必要なパッケージが反映されるので、 以下を実行し、パッケージをインストールする。npm install
参考
- Use Hugo Modules | Hugo
- Hugo Modules の仕組みで Hugo サイト用のコンテンツを分割して管理する - まくまく Hugo ノート
- kantas-spike/kantas-theme: Hugo theme for programming learner portfolio
- gitのsubmoduleを削除したい | kanta’s spike
-
Quick start | Hugoに従った方法である。 ↩︎
-
サイトはGitHubではなく、ローカルの
myblog
フォルダーで管理されているものとする。 ↩︎