UNPKG

1.77 kB Markdown View 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## Removal of Server Code
37
38Any server-only [Route Module APIs][route-module] will be removed from the bundles. Consider this route module:
39
40```tsx
41export async function loader() {
42 return { message: "hello" };
43}
44
45export async function action() {
46 console.log(Date.now());
47 return { ok: true };
48}
49
50export async function headers() {
51 return { "Cache-Control": "max-age=300" };
52}
53
54export default function Component({ loaderData }) {
55 return <div>{loaderData.message}</div>;
56}
57```
58
59After 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.
60
61[route-module]: ../start/framework/route-module