最近在玩Vite+Vue3的小專案Twitch NPC對話聊天室展示器,在測試的時候就是使用Github靜態部署,但是一直碰到奇奇怪怪的坑,就在這邊統整出來兩個比較大的問題:
Vue Router 使用 createWebHistory
時的注意事項 🔗
-
如果是部署在根目錄的情況下router設定應該使用
history: createWebHistory('/')
,有子路徑再跟著調整;
部署在Github Pages時URL通常是https://{user}.github.io/{repository}/
,對應的設定是history: createWebHistory('/{repository}/')
-
為了讓 GitHub Pages 在找不到路由時能 fallback 回 index.html,vite.config裡面加下面這段,就會在dist/靜態目錄生成和dist/index.html同樣內容的404.html用來fallback回index.html。
plugins: [
vue(),
{
name: 'copy-404',
closeBundle() {
fs.copyFileSync('dist/index.html', 'dist/404.html')
}
}
]
dist/index.html
中資源路徑錯誤 🔗
沒設base路徑直接上去Github Pages的話,js和css這些資源都會跳404error。
Vite 預設打包出來的 HTML 裡,CSS、JS 等資源的路徑是從根目錄開始的,但如果你部署在 GitHub Pages 上,網址會是:
https://{user}.github.io/{repository}/
必須加上對應的 base 路徑,確保所有資源能正確對應:
// vite.config.ts
base: '/{repository}/',