Capítulo 35 de 57

Chapter 35: Automatic Code Splitting

Core Idea

Automatic code splitting (autoCodeSplitting: true) transforms route files at dev/build time, rewriting them into lazy-loading wrappers so only the routes initially needed are bundled, with additional chunks loaded on demand as users navigate.

Key Concepts

  • Reference file: the original route file, transformed to use lazy-loading wrappers in place of directly exported route properties.
  • Virtual file: a minimal, on-the-fly generated file containing only the specific properties requested for a given split (e.g. just the component).
  • Default split groupings: by default, three separate chunks are created: the main component, the errorComponent, and the notFoundComponent.
  • Critical rule: route properties like component and loader should not be exported (re-exported for external use) from the route file, since doing so would force them back into the main application bundle.
  • codeSplitGroupings: a per-route property that lets you customize which properties are grouped into which chunks for that specific route.
  • splitBehavior: a programmatic function for custom, logic-driven control over splitting behavior, taking precedence over the global default but yielding to per-route codeSplitGroupings.
  • defaultBehavior: a global fallback option defining default splitting behavior for all routes that don't specify their own.
  • Loader splitting overhead: splitting the loader via this feature still introduces an additional network trip to fetch the loader's chunk before data fetching can begin, which can slow initial page loads.

Key Takeaways

  1. Automatic code splitting requires file-based routing plus a supported bundler plugin; it is a build/dev-time transform, not a runtime API.
  2. Three levels of customization exist, in order of precedence: per-route codeSplitGroupings > programmatic splitBehavior > global defaultBehavior.
  3. Never export component, loader, or other split-eligible route properties for reuse elsewhere in your app, doing so defeats the purpose by pulling them into the main bundle.
  4. Even with this feature, be cautious about opting into loader splitting since it adds a network round-trip before data loading starts.

Connects To

  • Ch 34: Code Splitting covers the manual .lazy.tsx alternative and the conceptual split between critical vs. non-critical route configuration that this automatic feature implements under the hood.