[Vue] 將Vue專案部署至Github Pages

Eric Chou
4 min readFeb 13, 2019
  1. 先至Github建立與本地專案名稱相同的repository,在此以eric-project為例

2. 接著到專案資料夾中新增vue.config.js (Vue CLI 3 需要自行新增),設定publicPath,當env為production時變更為eric-project,因為屆時Github Pages部署完成後的網址為https://chou0728.github.io/eric-project/,因此根目錄為eric-project

//vue.config.jsmodule.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/eric-project/'
: '/'
}

3. 將本地專案推送至雲端

git initgit remote add origin https://github.com/chou0728/eric-project.gitgit add .git commit -m "Initial commit"git push -u origin master

4. 在專案目錄下新增deploy.sh,Vue CLI 官方推薦用法,這是屬於 shell script (程式化腳本),在執行該腳本也時會自動幫你執行裡面的指令,當然,若偏好自行輸入指令也可以不用使用

//deploy.sh#!/usr/bin/env sh# 當發生錯誤時終止腳本運行
set -e
# 打包
npm run build
# 移動至到打包後的dist目錄
cd dist
git init //因為dist資料夾預設是被ignore的,因此在進入dist資料夾後初始化git
git add -A
git commit -m 'deploy'
# 部署到 https://github.com/chou0728/eric-project.git 分支為 gh-pages
git push -f https://github.com/chou0728/eric-project.git master:gh-pages
//將dist資料夾中的內容推送至遠端eric-project的gh-pages分支中,並強制無條件將舊有的內容取代成目前的內容(指令 git push -f)cd -

分支名稱會叫gh-pages是因為Github在部署時只允許三種來源(master, gh-pages, master/docs)

更多參考:

4. 執行腳本

sh ./deploy.sh

5. 執行完後,至Github頁面中會看到該專案多了一個branch叫做gh-pages

切換gh-pages分支後會看到裡面的內容跟本地中專案的dist資料夾內一樣

標準的靜態網頁部署結構

6. 進入settings頁面,在GitHub Pages的設定區中,將Source改為gh-pages,並按下儲存,接著靜待幾分鐘後,點選上方提供的連結就可以看見部署後的靜態網頁了!

--

--