我是參考此做法部屬 :
Deploy Vite React App on Both GitHub Pages and Vercel (robiul.dev)
會遇到一個問題,由於我有使用react-router,並且需要設定routes
與basename
const router = createBrowserRouter(routes, { basename: import.meta.env.BASE_URL });
如果直接參照他的寫法,可以部屬在vercel沒錯,但是當根目錄的”/”在github上會失敗的
為甚麼? 因為github根目錄是你repo的名稱,例如https://your-github-name.io//your-repo
,所以router的根目錄也要設定相同的/your-reop
而非/
,否則他會抓不到而拋出錯誤
為甚麼vercel可以? 因為Vercel的domain會是你的repo名稱,例如https://your-repo.vercel.app/
。所以此時router根目錄設定/
就好
最終修改會是
const router = createBroswerRouter([
path: import.meta.env.BASE_URL,
],{
basename: import.meta.env.BASE_URL
})
<aside>
✍️ import.meta.env.BASE_URL
抓的值會依照vite.config.js中base設定的值動態決定
因為我們在base會設定`process.env.VITE_BASE_PATH || “/your-repo”
process.env.VITE_BASE_PATH 是抓取vercel上設定的自訂易環境變數,所以在github上時不會有值! 而該變數會設定
/`
</aside>
由於我的專案有設定child route,所以在child route時,需要特別path做設定
//檢查是否有base path(在vercel上時為true)
const haveBasePath = import.meta.env.VITE_BASE_PATH ? true : false;
const router = createBroswerRouter([
path: import.meta.env.BASE_URL,
element: <Root/>
children: [
{
path: haveBasePath || "/Path1" : "Path1",
element: <Path1 />
}
]
],{
basename: import.meta.env.BASE_URL
})
<aside> ✍️ `path: haveBasePath || "/Path1" : "Path1"
haveBasePath = true時,此時在vercel上執行,路徑為
https://your-repo.vercel.app/ 此時
import.meta.env.BASE_URL為
/(絕對路徑),所以當子目錄再訪問時,也需要設定
/Path1(絕對路徑),才會導到正確的
https://your-repo.vercel.app/Path1
haveBasePath = false時,此時在github上執行,路徑為
https://name.github.io/your-repo 此時
import.meta.env.BASE_URL為
/your-repo(絕對路徑),所以當子目錄再訪問時,也需要設定
/your-reop/Path1(絕對路徑) 或是
Path1(相對路徑),才會是正確的
https://name.github.io/your-repo/Path1 為甚麼不能直接設定
/Path1呢? 由於
/Path1代表到根目錄
Path1找起,但是根目錄應該是
/your-repo才對,所以會發生錯誤訊息 :
Uncaught Error: Absolute route path "/" nested under path "/your-repo/" is not valid. An absolute child route path must start with the combined path of all its parent routes. 此錯誤訊息表示,你使用錯誤的絕對路徑方式,導致錯誤。 改使用
/your-reop/Path1(絕對路徑) 或是
Path1`(相對路徑)解決此問題
</aside>
ite.config.js會運行在server上,而當有設定base時,運行環境將會針對此設定進行資料提取,如果當你想在兩個環境執行時,必須確認根目錄。
例如vercel會運行在/
根目錄
而github會運行在/your-repo
你專案名稱的根目錄