| 1 | ---
|
| 2 | title: Automatic Code Splitting
|
| 3 | ---
|
| 4 |
|
| 5 | # Automatic Code Splitting
|
| 6 |
|
| 7 | [MODES: framework]
|
| 8 |
|
| 9 | <br/>
|
| 10 | <br/>
|
| 11 |
|
| 12 | When 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 |
|
| 16 | Consider this simple route config:
|
| 17 |
|
| 18 | ```tsx filename=app/routes.ts
|
| 19 | import {
|
| 20 | type RouteConfig,
|
| 21 | route,
|
| 22 | } from "@react-router/dev/routes";
|
| 23 |
|
| 24 | export default [
|
| 25 | route("/contact", "./contact.tsx"),
|
| 26 | route("/about", "./about.tsx"),
|
| 27 | ] satisfies RouteConfig;
|
| 28 | ```
|
| 29 |
|
| 30 | Instead of bundling all routes into a single giant build, the modules referenced (`contact.tsx` and `about.tsx`) become entry points to the bundler.
|
| 31 |
|
| 32 | Because 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 |
|
| 34 | If 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 |
|
| 38 | Any server-only [Route Module APIs][route-module] will be removed from the bundles. Consider this route module:
|
| 39 |
|
| 40 | ```tsx
|
| 41 | export async function loader() {
|
| 42 | return { message: "hello" };
|
| 43 | }
|
| 44 |
|
| 45 | export async function action() {
|
| 46 | console.log(Date.now());
|
| 47 | return { ok: true };
|
| 48 | }
|
| 49 |
|
| 50 | export async function headers() {
|
| 51 | return { "Cache-Control": "max-age=300" };
|
| 52 | }
|
| 53 |
|
| 54 | export default function Component({ loaderData }) {
|
| 55 | return <div>{loaderData.message}</div>;
|
| 56 | }
|
| 57 | ```
|
| 58 |
|
| 59 | After 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
|