想架設一個部落格用來分享筆記,主要使用 Hugo + Github Page,並記錄一下過程 🤔

Part 1: Setup Hugo

Installation

這裡透過 brew 來進行安裝

brew install hugo

查看 Hugo 版本確認是否安裝成功,這裡使用的版本是 v0.145.0

hugo version

New Hugo Site

建立新專案 hugo new site <your_project_name>

hugo new site blog

會產生以下的資料夾結構

.
├── archetypes
├── assets
├── content
├── data
├── hugo.toml
├── i18n
├── layouts
├── public
├── static
└── themes

調整設定檔 hugo.toml

baseURL = "https://<username>.github.io/" # your host
languageCode = "en"
title = "Your Blog Tttle"

Run Locally

Web Server is available at http://localhost:1313

hugo server

如果 baseURL 後面有設定路徑服務跑起來就會是 http://localhost:1313/blog

baseURL = "https://<username>.github.io/blog"

另外如果有需要分環境時,有提供參數可以指定要使用的設定檔

hugo --config other.toml

更多設定可以參考 Introduction

Add Theme: PaperMod

可以從這邊 Hugo Themes 挑選一個主題來安裝,這邊選擇 PaperMod 當作主要的主題

然後參考 Install / Update PaperMod 指引,這裡選擇使用 submodule 方式添加

git init

git submodule add --depth=1 https://github.com/adityatelange/hugo-PaperMod.git themes/PaperMod
git submodule update --init --recursive # needed when you reclone your repo (submodules may not get cloned automatically)

更新主題

git submodule update --remote --merge

將設定添加至 hugo.toml

theme = "PaperMod"

文件中有些會使用 .yaml 格式可以用這個工具轉換 YAML to TOML,反之如果是轉換成 .yaml 該工具也有提供

Theme Setting: Enable Home-Info Mode

[params.homeInfoParams]
title = "Your Title"
content = "Can be Info, links, about..."

[[params.socialIcons]]
name = "github"
url = "https://github.com/<username>" # your GitHub link

Theme Setting: Add Archives Page

Create a page with archive.md in content directory with following content

touch content/archives.md

and add the following to it

---
title: "Archive"
layout: "archives"
url: "/archives/"
summary: archives
---

Theme Setting: Add Search Page

Add the following to site config, hugo.toml

[outputs]
home = [ "HTML", "RSS", "JSON" ]

searchHidden = true

Create a page with search.md in content directory with following content

touch content/search.md

and add the following to it

---
title: "Search"
layout: "search"
summary: "search"
placeholder: "Type something"
---

如果文章不想要被搜尋的話,可以將設定加在該文章的屬性中。searchHidden = true 代表不會被搜尋到

+++
# ...
searchHidden = true
+++

Theme Setting: Add Menu

將設定添加至 hugo.toml

# Menu
[[menu.main]]
identifier = "categories"
name = "Categories"
url = "/categories/"
weight = 10

[[menu.main]]
identifier = "tags"
name = "Tags"
url = "/tags/"
weight = 20

[[menu.main]]
identifier = "archives"
name = "Archives"
url = "/archives/"
weight = 30

[[menu.main]]
identifier = "search"
name = "Search"
url = "/search/"
weight = 40

Properties

  • identifier: 唯一辨識符
  • name: 顯示名稱
  • url: 目標網址
  • weight: 排序權重,數字越小會越靠左

Theme Setting: Add Favicon

Favicon(s) can be generated by Favicon.io and can be simply put in /static folder

.
├── static/   <----- here
└── themes/
│   └── PaperMod/
├── hugo.toml

將設定添加至 hugo.toml

# favicon
[params.assets]
favicon = "/favicon/favicon.ico"
favicon16x16 = "/favicon/favicon-16x16.png"
favicon32x32 = "/favicon/favicon-32x32.png"
apple_touch_icon = "/favicon/apple-touch-icon.png"
safari_pinned_tab = "/favicon/safari-pinned-tab.svg"

Theme Setting: Add Comments

這裡選擇使用 giscus 這套開源的留言系統,是將留言紀錄至 GitHub Discussions 以達成這樣的功能

  1. Enabling or disabling GitHub Discussions for a repository
  2. 添加 GitHub APP
  3. 到官方網站 giscus 按照指引取得安裝程式碼

範例 comments.html

<script src="https://giscus.app/client.js"
        data-repo="[ENTER REPO HERE]"
        data-repo-id="[ENTER REPO ID HERE]"
        data-category="[ENTER CATEGORY NAME HERE]"
        data-category-id="[ENTER CATEGORY ID HERE]"
        data-mapping="pathname"
        data-strict="0"
        data-reactions-enabled="1"
        data-emit-metadata="0"
        data-input-position="bottom"
        data-theme="preferred_color_scheme"
        data-lang="en"
        crossorigin="anonymous"
        async>
</script>
  1. 將程式碼添加至 comments.html 並修改 hugo.toml

在指定的路徑下建立 comments.html

touch layouts/partials/comments.html

將設定添加至 hugo.toml

[params]
# ...
comments = true

Others Theme Setting

更多 Features 設定

[params]
showReadingTime = true
# showShareButtons = true
showToc = true
showBreadCrumbs = true
# showPostNavLinks = true
showCodeCopyButtons = true

Part 2: First Post

Create posts.md for Template

touch archetypes/posts.md
.
├── archetypes
│   ├── default.md
│   └── posts.md      <--- Create posts.md here
├── assets
├── content
│   ├── archives.md
│   └── search.md
├── hugo.toml

將設定添加至 posts.md

+++
date = '{{ .Date }}'
draft = false
title = '{{ replace .File.ContentBaseName "-" " " | title }}'
author = 'islu'
summary = ''
description = ''
keywords = []
categories = ['📝 Note']
tags = []
+++

這樣在建立 content/posts/ 路徑下的文章就會使用這個樣板填入以上預設的內容

Setup Cover Image

如果要添加封面圖片可以將設定添加至文章的 Metadata

+++
# ...
[cover]
image = "images/cover.png"
alt = ""
caption = ""
+++

How to display the cover image on /post #1447,可以調整是否在列表或文章顯示封面圖片

+++
# ...
[cover]
# ...
relative = false
hiddenInList = true
hiddenInSingle = false
+++

Add New Posts

前面步驟建立模板 archetypes/posts.md ,因此透過指令 cotent/posts/*.md 底下的文章會依照模板預先加入內容

hugo new posts/first-post.md
.
├── archetypes
│   ├── default.md
│   └── posts.md             <------ template here
├── assets
├── content
│   ├── archives.md
│   ├── posts
│   │   └── first-post.md    <------ here
│   └── search.md
├── hugo.toml

但是我這邊會選擇使用以下方式建立後,為了跟該文章會參考的圖片放在一起管理

hugo new posts/first-post/index.md
mkdir content/posts/first/images
.
├── archetypes
│   ├── default.md
│   └── posts.md
├── assets
├── content
│   ├── archives.md
│   ├── posts
│   │   └── first-post
│   │       ├── images       <------ here
│   │       │   └── cover.png
│   │       └── index.md     <------ and here
│   └── search.md
├── hugo.toml

而於文章引用圖片時就直接使用相對路徑引用就可以


![](images/cover.png)

Part 3: Push and Deploy to GitHub

Add .gitignore

新增 Hugo.gitignore

# Generated files by hugo
/public/
/resources/_gen/
/assets/jsconfig.json
hugo_stats.json

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

# Temporary lock file while building
/.hugo_build.lock

Host on GitHub Pages

Create a file named hugo.yaml in a directory named .github/workflows

mkdir -p .github/workflows
touch .github/workflows/hugo.yaml

Copy and paste the YAML below into the file you created. Change the branch name and Hugo version as needed

# Sample workflow for building and deploying a Hugo site to GitHub Pages
name: Deploy Hugo site to Pages

on:
  # Runs on pushes targeting the default branch
  push:
    branches:
      - main

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: "pages"
  cancel-in-progress: false

# Default to bash
defaults:
  run:
    shell: bash

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    env:
      HUGO_VERSION: 0.145.0
      HUGO_ENVIRONMENT: production
      TZ: America/Los_Angeles
    steps:
      - name: Install Hugo CLI
        run: |
          wget -O ${{ runner.temp }}/hugo.deb https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_extended_${HUGO_VERSION}_linux-amd64.deb \
          && sudo dpkg -i ${{ runner.temp }}/hugo.deb
      - name: Install Dart Sass
        run: sudo snap install dart-sass
      - name: Checkout
        uses: actions/checkout@v4
        with:
          submodules: recursive
          fetch-depth: 0
      - name: Setup Pages
        id: pages
        uses: actions/configure-pages@v5
      - name: Install Node.js dependencies
        run: "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true"
      - name: Cache Restore
        id: cache-restore
        uses: actions/cache/restore@v4
        with:
          path: |
            ${{ runner.temp }}/hugo_cache
          key: hugo-${{ github.run_id }}
          restore-keys:
            hugo-
      - name: Build with Hugo
        run: |
          hugo \
            --gc \
            --minify \
            --baseURL "${{ steps.pages.outputs.base_url }}/" \
            --cacheDir "${{ runner.temp }}/hugo_cache"
      - name: Cache Save
        id: cache-save
        uses: actions/cache/save@v4
        with:
          path: |
            ${{ runner.temp }}/hugo_cache
          key: ${{ steps.cache-restore.outputs.cache-primary-key }}
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: ./public

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    runs-on: ubuntu-latest
    needs: build
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

Push and Deploy

  1. Create a GitHub repository
  2. Push the changes to GitHub
git add .
git commit -m "init"
git branch -M main
git remote add origin <remote_repo_url>
git push -u origin main

Next Steps

Other things that can be done

Tool: tree

Display directories as trees

tree
tree -L 1 # 只顯示第一層
tree -d # 只顯示資料夾
tree -a # 會顯示隱藏資料夾