我有一个 React 应用程序(带有 vite 和 typescript),它在使用 npm run dev 时运行良好。主页也正确显示在 github 页面上。
但似乎一旦我尝试重定向到产品页面或联系页面,它就会给我一个 404。我是 React 的初学者,这真的让我感到困惑(特别是因为它在运行开发模式下工作得很好) .
App.tsx
import { BrowserRouter, Route, Routes } from "react-router-dom";
return (
<div>
<Header />
<Cart cartItems={cartItems} setCartItems={setCartItems} />
<Routes>
<Route path="/shopping-cart" element={<Main />} />
<Route
path="shopping-cart/products"
element={<Products setCartItems={setCartItems} />}
/>
<Route path="shopping-cart/contact" element={<Contact />} />
</Routes>
<Footer />
</div>
);
}
main.tsx:
import { BrowserRouter } from "react-router-dom";
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);
邀请配置:
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vitejs.dev/config/
export default defineConfig({
base: '/shopping-cart/',
plugins: [react()],
})
(完整代码https://github.com/Fibox-coder/shopping-cart)
我尝试了很多方法,比如使用 Switch 代替 Routes,使用 HashRouter 代替 BrowserRouter,但似乎没有任何效果。
单击导航栏时,我在 Github 页面上有 3 个 URL:
作品: 首页 = https://fibox-coder.github.io/shopping-cart/
404 找不到文件: 产品 = https://fibox-coder.github.io/shopping-cart/products/ 联系人 = https://fibox-coder.github.io/shopping-cart/contact
React App 必须为生产构建,所以你应该在 vitejs.dev 教程中使用 Github Action。这是我的方式,和我一起工作很好。
vite.config.js 中的Config 帮助自动设置基本路径:
import { defineConfig } from "vite";
import { fileURLToPath } from "url";
import path from "path";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"~": path.resolve(path.dirname(fileURLToPath(import.meta.url)), "src"),
},
},
base: process.env.NODE_ENV === "production" ? "/shopping-cart/" : "",
});
您应该使用 .github/workflows/gh-page.yml 创建 Github Action 以自动更新“gh-pages”分支:
name: Deploy GH Pages
on: push
jobs:
build-and-deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
with:
persist-credentials: false
- name: Install
run: yarn
- name: Build
run: yarn build
- name: Deploy
uses: JamesIves/github-pages-deploy-action@releases/v3
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages
folder: dist
转到设置 -> 页面 -> 将分支更改为与上面的 BRANCH 相同的“gh-pages”,并且仅在将代码推送到 Github 后工作(Github Action 创建“gh-pages”并在 Github Action 运行完成约 1 分钟后工作)
更多信息:https://vitejs.dev/guide/static-deploy.html#github-pages