GitHub Pages

在本教學中,我們使用 GitHub Actions 來部署 GitHub Pages。這適用於公開和私人儲存庫。如果您不想將原始碼資料夾上傳到 GitHub,請跳至「一鍵部署」章節。

  1. 建立一個名為 username.github.io 的儲存庫,其中 username 是您在 GitHub 上的使用者名稱。如果您已上傳到另一個儲存庫,請改為重新命名該儲存庫。
  2. 將您的 Hexo 資料夾中的檔案推送到您儲存庫的預設分支。預設分支通常是 main,較舊的儲存庫可能使用 master 分支。
  • main 分支推送到 GitHub

    $ git push -u origin main
  • 預設情況下,public/ 資料夾不會(且不應)上傳,請確保 .gitignore 檔案包含 public/ 行。資料夾結構應該大致類似於此儲存庫

  1. 使用 node --version 檢查您在本機上使用的 Node.js 版本。記下主要版本(例如,v20.y.z)。
  2. 在您的 GitHub 儲存庫設定中,導覽至 Settings > Pages > Source。將來源變更為 GitHub Actions 並儲存。
  3. 在您的儲存庫中建立 .github/workflows/pages.yml,並包含以下內容(將 20 替換為您在上一步中記下的 Node.js 主要版本)。
.github/workflows/pages.yml
name: Pages

on:
push:
branches:
- main # default branch

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
token: ${{ secrets.GITHUB_TOKEN }}
# If your repository depends on submodule, please see: https://github.com/actions/checkout
submodules: recursive
- name: Use Node.js 20
uses: actions/setup-node@v4
with:
# Examples: 20, 18.19, >=16.20.2, lts/Iron, lts/Hydrogen, *, latest, current, node
# Ref: https://github.com/actions/setup-node#supported-version-syntax
node-version: "20"
- name: Cache NPM dependencies
uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.OS }}-npm-cache
restore-keys: |
${{ runner.OS }}-npm-cache
- name: Install Dependencies
run: npm install
- name: Build
run: npm run build
- name: Upload Pages artifact
uses: actions/upload-pages-artifact@v3
with:
path: ./public
deploy:
needs: build
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
  1. 部署完成後,請檢查 username.github.io 上的網頁。

注意 - 如果您使用 CNAME 指定了自訂網域名稱,則需要將 CNAME 檔案新增到 source/ 資料夾。更多資訊

專案頁面

如果您希望在 GitHub 上擁有專案頁面

  1. 導覽至您在 GitHub 上的儲存庫。前往 Settings 標籤。變更 Repository name,讓您的部落格可以在 username.github.io/repository 上存取,repository 可以是任何名稱,例如 bloghexo
  2. 編輯您的 _config.yml,將 url: 值變更為 https://username.github.io/repository
  3. 在您的 GitHub 儲存庫設定中,導覽至 Settings > Pages > Source。將來源變更為 GitHub Actions 並儲存。
  4. 提交並推送到預設分支。
  5. 部署完成後,請檢查 username.github.io/repository 上的網頁。

一鍵部署

以下說明改編自一鍵部署頁面。

  1. 安裝 hexo-deployer-git
  2. 將以下設定新增至 _config.yml (如果有的話,請移除現有的行)。
deploy:
type: git
repo: https://github.com/<username>/<project>
# example, https://github.com/hexojs/hexojs.github.io
branch: gh-pages
  1. 執行 hexo clean && hexo deploy
  2. 檢查 username.github.io 上的網頁。

實用連結