UNPKG

2.56 kB Markdown View Raw
1---
2title: Automatic Code Splitting
3---
4
5# Automatic Code Splitting
6
7[MODES: framework]
8
9When using React Router's framework features, your application is automatically code split to improve the performance of initial load times when users visit your application.
10
11## Code Splitting by Route
12
13Consider this simple route config:
14
15```tsx filename=app/routes.ts
16import {
17 type RouteConfig,
18 route,
19} from "@react-router/dev/routes";
20
21export default [
22 route("/contact", "./contact.tsx"),
23 route("/about", "./about.tsx"),
24] satisfies RouteConfig;
25```
26
27Instead of bundling all routes into a single giant build, the modules referenced (`contact.tsx` and `about.tsx`) become entry points to the bundler.
28
29Because these entry points are coupled to URL segments, React Router knows just from a URL which bundles are needed in the browser, and more importantly, which are not.
30
31If the user visits `"/about"` then the bundles for `about.tsx` will be loaded but not `contact.tsx`. This drastically reduces the JavaScript footprint for initial page loads and speeds up your application.
32
33## Route Module Splitting
34
35React Router can also split client-side route exports (`clientLoader`, `clientAction`, `clientMiddleware`, `HydrateFallback`) into separate chunks that can be loaded independently from the route component.
36
37This allows these exports to be fetched and executed while the component code is still downloading, improving performance for client-side data loading.
38
39This behavior is enabled by default. You can set `splitRouteModules` to `false` to opt out, or `"enforce"` to require all routes to be splittable. The `"enforce"` option will cause build failures for routes that cannot be split due to shared code.
40
41```ts filename=react-router.config.ts
42import type { Config } from "@react-router/dev/config";
43
44export default {
45 splitRouteModules: false,
46} satisfies Config;
47```
48
49## Removal of Server Code
50
51Any server-only [Route Module APIs][route-module] will be removed from the bundles. Consider this route module:
52
53```tsx
54export async function loader() {
55 return { message: "hello" };
56}
57
58export async function action() {
59 console.log(Date.now());
60 return { ok: true };
61}
62
63export async function headers() {
64 return { "Cache-Control": "max-age=300" };
65}
66
67export default function Component({ loaderData }) {
68 return <div>{loaderData.message}</div>;
69}
70```
71
72After building for the browser, only the `Component` will still be in the bundle, so you can use server-only code in the other module exports.
73
74[route-module]: ../start/framework/route-module