GitHub Demo 地址
在線預覽
參考文章
使用GithubActions發(fā)布Vue網(wǎng)站到GithubPage
使用Github Actions將Vue項目部署到Github Pages
前端使用github pages 部署自己的網(wǎng)站
GitHub Actions自動化部署前端項目指南
前言
vue前端項目寫好之后,想部署到線上通過在線地址進行訪問,可以通過gitee或者GitHub的pages
這里是手動部署的方法:Vue - vue項目打包部署到Github的pages在線訪問
自動化部署需要的準備工作
在項目中設置路徑
在vite.config.ts文件設置base為 './',

添加gh-pages分支
新增一個代碼分支,命名為
gh-pages,如果不是空白分支,把分支多余的代碼刪掉
然后復制dist里面的文件(不要dist文件夾)到項目根目錄
提交代碼到分支
設置pages
進入GitHub-項目-settings-pages設置,即可得到在線預覽地址

創(chuàng)建自動部署的文件
在項目根路徑創(chuàng)建.github\workflows\auto-deploy.yml文件
# .github/workflows/auto-deploy.yml
name: auto deploy ??
on:
# 監(jiān)聽push操作
push:
branches:
- main # 這里只配置了main分支,所以只有推送main分支才會觸發(fā)以下任務
pull_request:
# 這個選項可以使你手動在 Action tab 頁面觸發(fā)工作流
# workflow_dispatch:
permissions:
# 允許對倉庫的內容進行寫操作。包括創(chuàng)建、修改和刪除文件、目錄以及提交更改等
# 這里只配置了push,所以只有推送main分支才會觸發(fā)以下任務
contents: write
# 允許管理 GitHub Pages 服務并對其進行寫操作
pages: write
jobs:
# 任務ID
build-and-deploy:
# 運行環(huán)境
# runs-on: macos-latest
# runs-on: windows-latest
runs-on: ubuntu-latest
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
# 步驟
steps:
# 官方action,將代碼拉取到虛擬機
- name: Checkout
uses: actions/checkout@v3
# 建一個名為setup-node的步驟(安裝指定版本的Node.js)
- name: setup-node
# 使用setup-node@v3這個action
uses: actions/setup-node@v3
# 指定某個action 可能需要輸入的參數(shù)
with:
node-version: '16.x'
# 安裝 pnpm
- name: Install pnpm
run: npm install pnpm -g
# 安裝依賴
- name: Install dependencies
run: pnpm i
# 打包
- name: Build application ??
run: pnpm run build:prod
# 部署 https://github.com/JamesIves/github-pages-deploy-action
- name: Deploy ??
uses: JamesIves/github-pages-deploy-action@v4
if: github.ref == 'refs/heads/main'
with:
token: ${{ secrets.GITHUB_TOKEN }}
branch: gh-pages # default: gh-pages
folder: dist
clean: true # Automatically remove deleted files from the deploy branch
# commit-message: ${{ github.event.head_commit.message }} # default: `Deploying to gh-pages from @ 3238feb ??`
# commit-message: "deploy: ${{ github.sha }} (${{ github.event.head_commit.message }}) ?? "
獲取密鑰并存儲到Github倉庫中
創(chuàng)建密鑰
進入Github的Settings中https://github.com/settings/,依次點擊Developer settings、Personal access tokens。然后點擊Generate new token創(chuàng)建。因為要操作倉庫,所以需要勾選repo權限。
具體請參考:github 創(chuàng)建個人訪問令牌
請及時保存生成的密鑰
將密鑰存儲到Github倉庫
首先創(chuàng)建一個Github倉庫,然后到倉庫的
Settings/Secret下,點擊New repository secret將剛才保存的密鑰保存,并命名為ACCESS_TOKEN(注意,如果這里的命名更改了,前面的yml文件中的${{ secrets.ACCESS_TOKEN }}也要更改)
完成這些步驟后,當你將新代碼推送到 GitHub 倉庫的主分支(通常是 main)時,GitHub Actions 將會自動運行,并將構建后的靜態(tài)文件部署到 gh-pages 分支。然后,你可以通過訪問 https://<用戶名>.github.io/<倉庫名稱>/ 來查看部署好的 Vue 項目。

