v6路由懒加载配置踩坑:代码分割策略与优化实践
React Router v6的发布带来了许多新特性,其中路由懒加载(Code Splitting)的实现方式发生了显著变化。在实际升级过程中,我们遇到了一些配置上的坑,特此总结分享。
问题背景
在v5版本中,我们通过react-loadable库实现路由懒加载,但在v6中,官方推荐使用React内置的lazy和Suspense特性。然而,在实际应用中,简单的配置方式并不能满足所有场景需求。
核心踩坑点
1. 基础懒加载配置
import { BrowserRouter, Routes, Route, lazy, Suspense } from 'react-router-dom';
const LazyComponent = lazy(() => import('./components/LazyComponent'));
function App() {
return (
<BrowserRouter>
<Suspense fallback="加载中...">
<Routes>
<Route path="/" element={<LazyComponent />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
2. 多级路由懒加载 在实际项目中,我们遇到了多级路由的懒加载问题。正确的做法是:
const LazyComponent = lazy(() => import('./components/LazyComponent'));
const LazySubComponent = lazy(() => import('./components/sub/LazySubComponent'));
<Route path="/parent" element={<LazyComponent />}>
<Route path="child" element={<LazySubComponent />} />
</Route>
3. 路由配置优化 为了更好地管理路由,建议将路由配置抽离到单独文件:
// routes.js
const routes = [
{
path: '/home',
element: lazy(() => import('./pages/Home'))
}
];
解决方案
通过合理的代码分割策略,配合路由懒加载,有效提升应用初始加载性能。建议在实际项目中根据业务需求调整懒加载粒度。

讨论