我正在使用 React/Vite/Express 构建一个托管在子目录中的应用程序。举个例子,假设它托管在:https://example.com/my/app/
在我的 Vite 配置中,我将
base
设置为 ./
export default defineConfig({
base: './',
build: {
outDir: './public/build',
},
plugins: [react()],
css: {
preprocessorOptions: {
scss: {
implementation: sass,
},
},
}
});
我也在使用react-router-dom。这是我的
createBrowserRouter
配置:
export const router = createBrowserRouter(
[
{
path: '/',
element: <App />,
errorElement: <Error />,
children: [
{
path: '/',
element: <Home />,
},
{
path: '/test1',
element: <Test1 />,
},
{
path: '/test2',
element: <Test2 />,
},
],
},
],
{
basename: '/my/app',
},
);
当我访问带有
/
的页面时,它工作得很好,例如https://example.com/my/app/
但是,如果我使用
https://example.com/my/app
删除尾随应用程序,Vite 会认为基础目录是父目录 /my/
并将其用作根目录。 React JS 和 CSS 然后抛出 404。
Vite 有没有办法解决这个问题,而不需要将完整路径硬编码为
base
,或者这是我需要在服务器上修复的问题,以重定向到带有尾部斜杠的 URL?
我不想对基础进行硬编码,因为它会根据环境而变化。不过,如果这是最佳实践方法,我会采用该解决方案。
我预计应用程序会假设
my/app
是一个目录。相反,它似乎使用 my/
作为目录。我尝试将 base
更改为 .
并更改为空字符串,但没有成功。
试试这个:
export const router = createBrowserRouter(
[
{
element: <App />,
errorElement: <Error />,
children: [
{
index: true,
element: <Home />,
},
{
path: '/test1',
element: <Test1 />,
},
{
path: '/test2',
element: <Test2 />,
},
],
},
],
{
basename: '/my/app',
},
);
basename
值应有前导斜杠且无尾部斜杠:'"/my/app"
index: true
而不是 path: '/'
path
前往 <App>
路线