將 Vue.js 專案發布至 GitHub Pages

Lisa Li
木棉草工作室
Published in
6 min readNov 14, 2023

2023.11.14

原由

目前 github 上的 Vue 相關開發 reposity 在當初上傳時沒有建立 github page 因此較難以展示,故想藉由這次機會上傳並將發布的流程寫成文件。

方法一

  1. vue.config.js 修改 public path
module.exports = defineConfig({
...
publicPath: process.env.NODE_ENV === 'production'
? '<--repository name-->' // ex: '/the_f2e_2022_week1/'
: '/'
})

2. npm run build 建立 發佈專案,因每次發佈都會重置 git,所以皆需要從頭綁定

# 打包
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)

參考:

方法二:使用 gh-pages 發布

前置準備

  1. 完成開發的專案
  2. 建立存放專案的 GitHub Repository

1. 安裝 gh-pages

npm install gh-pages --save-dev

💡 可能遇到的問題:
Que: eslint-plugin-vue 版本衝突
圖為本機上的版本比專案使用的版本新,導致衝突無法安裝

eslint-plugin-vue 版本衝突

Ans: 修改 package.json 中 eslint-plugin-vue 版本為 ^7.0.0 即可安裝

2. gh-pages 相關設定

確認專案在 github 上的路徑

可從 Github Repository 中察看
範例為: https://github.com/cottongrass0828/data_add_serial_number.git

建立 ghpages.js 並放在相對路徑中

範例中將檔案放置 資料夾 deploy 中

請記得將 options 中的 repo 改為 上方查閱到的路徑

// place at : deploy/ghpages.js
// you can see more info at <https://github.com/tschaub/gh-pages>
const path = require('path');
const ghpages = require('gh-pages');
const options = {
branch: 'gh-pages',
repo: '<https://github.com/cottongrass0828/data_add_serial_number.git>' // project github repo
};
const callback = err => {
if (err) console.error(err);
else console.log('publish success');
};
/**
* This task pushes to the `master` branch of the configured `repo`.
*/
ghpages.publish(path.resolve(__dirname, '../dist'), options, callback);

package.json 中的 scripts 新增 deploy 的用法

"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
/* './deploy/ghpages.js'為上方檔案建立的位置 */
+ "deploy": "npm run build && node ./deploy/ghpages.js"
},

修改發布後根目錄的位置

由於 github-pages 顯示的預設網址為
https://<--github 帳號-->.github.io/<--資料庫名稱-->
所以在
vue.config.js 調整發布後網頁根目錄

module.exports = defineConfig({
//可使用 **process.env.NODE_ENV** 來判斷是否為發布而修改發佈位置
publicPath: process.env.NODE_ENV === 'production'
? '/data_add_serial_number/'
: '/'
})

一鍵部屬

設定完成後,之後只需要透過 npm run deploy 就可以直接部屬到 GitHub Pages 上囉!

npm run deploy

發布後需等待一段時間,才會顯示在 GitHub Pages 中

可以至 Setting 中的 Pages 標籤查看,如果有顯示網址就代表已經成功囉!

Setting 中的 Pages 標籤

小技巧

有 GitHub Pages 的專案,可以在 About 這邊設定顯示網址,方便他人瀏覽時直接連結至 GitHub Page 哦~

如果有 GitHub Page 的 Repository 就會有下方的 Checkbox 可以直接打勾,就會幫你套用網址,很方便!

--

--