Hexo 是基於 Node.js 的靜態網站產生器,專門針對部落格設計。產出純 HTML/CSS/JS,不需要後端或資料庫,部署到 GitHub Pages 完全免費。這篇記錄從安裝到上線的完整流程,以及幾個實際會踩到的坑。

安裝

先確認電腦上有 Node.js 和 npm,然後全域安裝 Hexo CLI:

1
npm install -g hexo-cli

建立新專案:

1
2
3
hexo init my-blog
cd my-blog
npm install

hexo init 會拉一套預設骨架,包含設定檔 _config.yml、範例文章、以及預設主題 landscape。

寫文章

1
hexo new "我的第一篇文章"

指令執行後會在 source/_posts/ 下產生一個 Markdown 檔,開頭是 front-matter(title、date、tags 等 YAML 區塊),內容用 Markdown 寫就行。

部署到 GitHub Pages

建立 Repository

GitHub Pages 的 repository 命名有規則:

  • 個人站username.github.io):repository 必須命名為 username.github.io,Pages 來源用 main 分支。
  • 專案站username.github.io/project-name):repository 名稱隨意,建議用 gh-pages 分支存放產生的靜態檔。

建完 repository 後,到 Settings → Pages,確認已啟用並選定正確的來源分支。

設定 _config.yml

修改專案根目錄的 _config.yml,找到 deploy 區塊:

1
2
3
4
deploy:
type: git
repo: https://github.com/username/username.github.io.git
branch: main # 個人站用 main;專案站用 gh-pages

repo 也可以用 SSH 格式(git@github.com:username/username.github.io.git),SSH 設定好之後部署不需要輸入密碼。

安裝部署套件

1
npm install hexo-deployer-git --save

執行部署

1
hexo deploy

底層是 git push,認證方式取決於你的 git 設定:

  • SSH key:設好後完全靜默,不會提示任何輸入。
  • HTTPS + credential helper:首次可能提示輸入 GitHub 帳號密碼或 Personal Access Token,之後由系統憑證管理員快取。
  • HTTPS 但沒有 credential helper:每次都會要求輸入,這種情況建議改 SSH 或設定 ~/.netrc

日常更新流程

每次改完文章後,依序跑三個指令:

1
2
3
hexo clean    # 清掉上次產生的靜態檔,避免快取殘留
hexo generate # 重新產生靜態頁面
hexo deploy # 推到 GitHub

generatedeploy 可以合併成一步:

1
hexo g -d

換主題(以 NexT 為例)

Hexo 預設主題是 landscape,主題列表在 hexo.io/themes。這裡用 NexT 示範。

將主題 clone 到 themes/next

1
git clone https://github.com/next-theme/hexo-theme-next themes/next

修改 _config.yml,把主題從 landscape 換掉:

1
2
theme: next
language: zh-TW

NexT v8+ 建議用 Alternate Theme Config:在專案根目錄建立 _config.next.yml,把 NexT 的主題設定(配色、選單、社交連結等)寫在這裡,而不是直接改 themes/next/_config.yml。這樣升級主題時不會覆蓋你的設定。

然後啟動本機預覽:

1
hexo server

CRLF 換行問題(Windows)

在 Windows 上執行 hexo deploy 時,可能會看到這類警告:

1
warning: LF will be replaced by CRLF in ...

原因是 Windows 預設行尾是 \r\n(CRLF),Linux/macOS 是 \n(LF),git 在轉換時會發出警告。

快速修法——全域關掉自動轉換:

1
git config --global core.autocrlf false

注意這是全域設定,會影響你電腦上所有的 git repository。如果只想對這個專案生效,在專案根目錄加一個 .gitattributes

1
* text=auto eol=lf

設定後重新部署即可。