Route Based

patternsdev/skills/javascript/route-based

作者 patternsdev48bf58a488cdMIT253 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5个月前更新

Teaches route-based code splitting for single-page applications. Use when different routes load distinct feature sets and you want to avoid loading all route code upfront.

AI 生成的概览

讲解单页应用基于路由的代码分割,按路由懒加载组件以减少首屏加载量。

功能
该技能提供单页应用基于路由进行代码分割的指导。它说明如何将 React Suspense 或 loadable-components 与 react-router 等路由库结合,按路由懒加载页面级组件。它还指出 Next.js、Remix 和 React Router 等框架已内置支持,并介绍在自定义配置中使用 React.lazy() 配合 Suspense,或按路由设置打包入口。
适用场景
当应用包含多个路由、且并非每个页面都需要全部代码时使用。其目的是只请求当前路由所需的代码包,从而缩短初始加载时间。
运行要求
不包含脚本或工具,仅为说明性指导。实践该指导需要 JavaScript 或 TypeScript 单页应用、路由库,以及可选的 React Suspense、loadable-components 或按路由配置入口的打包工具。

Route Based Splitting

We can request resources that are only needed for specific routes, by adding route-based splitting. By combining React Suspense or loadable-components with libraries such as react-router, we can dynamically load components based on the current route.

By lazily loading the components per route, we're only requesting the bundle that contains the code that's necessary for the current route. Since most people are used to the fact that there may be some loading time during a redirect, it's the perfect place to lazily load components!

When to Use

  • Use this when your application has multiple routes and not all code is needed on every page
  • This is helpful for reducing initial load time by only loading code for the current route

Instructions

  • Combine React Suspense or loadable-components with routing libraries like react-router
  • Lazily load page-level components per route for optimal code splitting
  • Take advantage of natural loading pauses during route transitions for a seamless experience

Details

By lazily loading the components per route, only the bundle containing code necessary for the current route is requested. Since users expect some loading time during navigation, route transitions are a natural place to introduce code splitting without degrading the experience.

Most modern frameworks (Next.js, Remix, React Router) support route-based splitting out of the box. In a custom setup, use React.lazy() with Suspense to wrap route-level components, or configure your bundler's entry points per route.

Source

来源与署名

来源:patternsdev/skills位于javascript/route-based提交48bf58a

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架