在本篇文章中,我們將討論如何使用GitHub Actions將Hugo靜態網站部署到GitHub Pages。GitHub Actions是GitHub提供的自動化功能,可讓您直接在GitHub儲存庫中建立自訂的軟體開發工作流程。透過使用GitHub Actions,您可以輕鬆自動化建置並將Hugo靜態網站部署到GitHub Pages的整個流程。
設定GitHub Pages
在使用GitHub Actions成功將Hugo靜態網站部署到GitHub Pages之前,您需要先為專案設定GitHub Pages。
- 前往您的GitHub專案頁面,點選右上角的「Settings」頁籤。
- 向下捲動至「Pages」區塊。
- 在「Build and deployment」設定中,找到「Source」下拉選單。
- 從可用選項中選擇「GitHub Actions」。這會告知GitHub Pages使用由GitHub Actions產生的成品進行部署。
完成GitHub Pages設定後,您的網站將使用hugo.yaml檔案中定義的工作流程進行部署。
設定GitHub Pages工作流程
若要使用Hugo和GitHub Actions設定GitHub Pages工作流程,請依照以下步驟操作:
- 在Hugo網站儲存庫的
.github/workflows/目錄中,建立名為hugo.yaml的新檔案。 - 將以下YAML設定複製到
hugo.yaml檔案中:
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.111.3
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 Embedded
run: sudo snap install dart-sass-embedded
- name: Checkout
uses: actions/checkout@v3
with:
submodules: recursive
fetch-depth: 0
- name: Setup Pages
id: pages
uses: actions/configure-pages@v3
- name: Install Node.js dependencies
run: "[[ -f package-lock.json || -f npm-shrinkwrap.json ]] && npm ci || true"
- name: Build with Hugo
env:
# For maximum backward compatibility with Hugo modules
HUGO_ENVIRONMENT: production
HUGO_ENV: production
run: |
hugo \
--gc \
--minify \
--baseURL "${{ steps.pages.outputs.base_url }}/"
- name: Upload artifact
uses: actions/upload-pages-artifact@v1
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@v2
此設定檔會建立一個工作流程,當您推送至main分支或從Actions頁籤手動執行工作流程時,它將建置您的Hugo靜態網站並部署至GitHub Pages。
結論
透過設定專案中的GitHub Pages,並使用提供的hugo.yaml工作流程設定,您可以輕鬆自動化建置並將Hugo靜態網站部署到GitHub Pages的整個流程。善用GitHub Actions,您可以專注於創作內容及更新網站,而無需每次手動部署。這套設定也讓您能夠充分利用GitHub Actions提供的內建CI/CD功能,進一步改善您的開發工作流程。
Source code : https://github.com/hobbyworker/hugo-demo