最近使用react+ts+vite进行打包,用到vite非根目录打包到nginx白屏的问题。
开始以为是vite的锅,配置半天vite.config.ts 中的base,也不好使,最后发现是react-router-dom中的useRoutes v6版本的锅。
下面为我的解决方案,比如我nginx的非根目录为/test-react,首先将vite.config.ts中的base设置 base:'/test-react/',
之前的代码
const routeList: Partial[] = [
{
path: '/auth/login',
element: ,
},
{
path: '/login',
element: ,
},
{
path: '/todolist',
element: ,
},
{
path: '/users',
element: ,
},
{
path: '/protablelist',
element: ,
},
{
path: '/500',
element: ,
},
{
path: '/',
element: ,
children: [
{
path: '/dashboard',
element: ,
},
{
path: '/project/list',
element: ,
},
{
path: '*',
element: ,
},
],
},
];
const RenderRouter: FC = () => {
const element = useRoutes(routeList);
return element;
};
export default RenderRouter;
然后将useRoutes相关的更改为以下代码:
const routeList: Partial[] = [
{
path: '/auth/login',
element: ,
},
{
path: '/login',
element: ,
},
{
path: '/todolist',
element: ,
},
{
path: '/users',
element: ,
},
{
path: '/protablelist',
element: ,
},
{
path: '/500',
element: ,
},
{
path: '/',
element: ,
children: [
{
path: '/dashboard',
element: ,
},
{
path: '/project/list',
element: ,
},
{
path: '*',
element: ,
},
],
},
];
// 设置总路由地址,防止非根目录部署找不到目录,造成白屏
const setBaseRouteUrl = (routeList:Partial[]) => {
let baseurl = import.meta.env.BASE_URL;
if(baseurl[baseurl.length-1]=='/'){
baseurl = baseurl.substring(0, import.meta.env.BASE_URL.lastIndexOf('/'));
}
routeList.map(item=>{
item.path = baseurl+item.path;
});
}
const RenderRouter: FC = () => {
setBaseRouteUrl(routeList);
const element = useRoutes(routeList);
return element;
};
export default RenderRouter;
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)