UNPKG

2.57 kBMarkdownView Raw
1---
2title: Automatic Code Splitting
3---
4
5# Automatic Code Splitting
6
7[MODES: framework]
8
9<br/>
10<br/>
11
12When 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.
13
14## Code Splitting by Route
15
16Consider this simple route config:
17
18```tsx filename=app/routes.ts
19import {
20 type RouteConfig,
21 route,
22} from "@react-router/dev/routes";
23
24export default [
25 route("/contact", "./contact.tsx"),
26 route("/about", "./about.tsx"),
27] satisfies RouteConfig;
28```
29
30Instead of bundling all routes into a single giant build, the modules referenced (`contact.tsx` and `about.tsx`) become entry points to the bundler.
31
32Because 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.
33
34If 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.
35
36## Route Module Splitting
37
38React Router can also split client-side route exports (`clientLoader`, `clientAction`, `clientMiddleware`, `HydrateFallback`) into separate chunks that can be loaded independently from the route component.
39
40This allows these exports to be fetched and executed while the component code is still downloading, improving performance for client-side data loading.
41
42This 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.
43
44```ts filename=react-router.config.ts
45import type { Config } from "@react-router/dev/config";
46
47export default {
48 splitRouteModules: false,
49} satisfies Config;
50```
51
52## Removal of Server Code
53
54Any server-only [Route Module APIs][route-module] will be removed from the bundles. Consider this route module:
55
56```tsx
57export async function loader() {
58 return { message: "hello" };
59}
60
61export async function action() {
62 console.log(Date.now());
63 return { ok: true };
64}
65
66export async function headers() {
67 return { "Cache-Control": "max-age=300" };
68}
69
70export default function Component({ loaderData }) {
71 return <div>{loaderData.message}</div>;
72}
73```
74
75After 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.
76
77[route-module]: ../start/framework/route-module