Skip to content

Tanstack Router ‐ Code Splitting (lazy load)

이재영 edited this page Mar 20, 2025 · 15 revisions

Automatic Code Splitting

Code Splitting | TanStack Router React Docs

  • 사용 중인 bundler(우리는 vite)의 config 파일에 Tanstack Router Bundler 플러그인을 추가하면, Tanstack Router의 code splitting 정책에 따라 자동으로 code splitting 해 줌
    • 초기 설정 이후에는 개발자가 code splitting을 위해 건드려야 할 것이 아무것도 없음 → benefit!
// vite.config.js

import { TanStackRouterVite } from '@tanstack/router-plugin/vite';
import react from '@vitejs/plugin-react';

...

export default defineConfig({
  plugins: [
    TanStackRouterVite({ 
      autoCodeSplitting: true,
      routeFileIgnorePrefix: '@',
      routesDirectory: './src/routes',
      generatedRouteTree: './src/routeTree.gen.ts',
    }),

...
  • Automatic Code Splitting이 지원되는 번들러
    • Vite
    • Rspack/Rsbuild
    • Webpack
    • Esbuild
  • 추가적으로, 개발자가 Automatic Code Splitting를 제어하기 위한 option들이 존재하는 것 같으나 그 부분에 대한 공식 문서가 현 시점(25-03-19)에는 아직 작성되지 않았음

https://tanstack.com/router/latest/docs/framework/react/guide/automatic-code-splitting

We'll be filling in this guide soon about the wonderful world of automatic code splitting with TanStack Router and the many customization options available to you. Stay tuned!

Manual Code Splitting

Code Splitting | TanStack Router React Docs

사용 중인 번들러가 Tanstack Router Bundler 플러그인을 지원하지 않아 automatic code-splitting을 사용하지 못하는 경우에는, 아래와 같은 방법으로 code splitting을 적용할 수 있음

https://tanstack.com/router/latest/docs/framework/react/guide/code-splitting#using-the-lazytsx-suffix

If you are not able to use the automatic code-splitting feature, you can still code-split your route files using the .lazy.tsx suffix. It is as easy as moving your code into a separate file with a .lazy.tsx suffix and using the createLazyFileRoute function instead of createFileRoute.

.lazy.tsx Suffix

  • 라우트 정의 시에 createFileRoute 대신 createLazyFileRoute를 사용해야 함
  • 라우트 파일명에 .lazy suffix를 붙여주면, 해당 라우트에 대해 code splitting이 적용됨
// code splitting 미적용 라우트
someRoute.tsx

// code splitting 적용
someRoute.lazy.tsx

한 라우트에서 route.tsxroute.lazy.tsx 를 함께 사용하기

  • code splitting을 적용하지 않을 파일들은 route.tsx에 작성하고, code splitting을 적용할 파일들은 route.lazy.tsx에 작성하는 방식으로 유연하게 code splitting을 사용할 수 있음

https://tanstack.com/router/latest/docs/framework/react/guide/code-splitting#using-the-lazytsx-suffix

When you are using .lazy.tsx you can split your route into two files to enable code splitting:

Before (Single File)

// src/routes/posts.tsx
import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from './api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
  component: Posts,
})

function Posts() {
  // ...
}

After (Split into two files)

This file would contain the critical route configuration:

// src/routes/posts.tsx

import { createFileRoute } from '@tanstack/react-router'
import { fetchPosts } from './api'

export const Route = createFileRoute('/posts')({
  loader: fetchPosts,
})

With the non-critical route configuration going into the file with the .lazy.tsx suffix:

// src/routes/posts.lazy.tsx
import { createLazyFileRoute } from '@tanstack/react-router'

export const Route = createLazyFileRoute('/posts')({
  component: Posts,
})

function Posts() {
  // ...
}
  • 위 예시에서 loader는 code splitting 할 수 없으므로 loadercreateFileRoute로 정의하고, 컴포넌트는 createLazyFileRoute에 정의하여 code splitting을 적용하도록 함
  • 결과적으로, post 라우트를 post.tsx, post.lazy.tsx 두 개의 파일로 관리하게 됨

결론

우리 프로젝트는 번들러로 Vite를 사용하고, Automatic Code Splitting이 지원되므로 이걸 사용하면 된다! (사실 처음부터 .lazy suffix를 사용할 필요가 없었음)

Code Splitting 적용 시 성능 변화 추이

테스트 환경

  • /home 라우트
  • development 모드
  • Lighthouse 사용

Code Splitting 미적용 시

b-1

테스트 결과

Iteration First Contentful Paint (s) Largest Contentful Paint (s) Total Blocking Time (ms) Speed Index (s) Performance Score
1 3.8 7.9 40 4.0 56
2 3.8 7.9 50 4.0 56
3 3.8 7.9 50 4.0 56
4 3.8 7.9 40 4.0 56
5 3.8 7.9 40 4.0 56
평균 3.8 7.9 44 4.0 56

Code Splitting 적용 시

a-2

테스트 결과

Iteration First Contentful Paint (s) Largest Contentful Paint (s) Total Blocking Time (ms) Speed Index (s) Performance Score
1 3.0 6.5 90 3.3 58
2 2.7 5.8 50 2.7 61
3 2.7 5.7 60 2.7 61
4 2.7 5.8 40 2.7 61
5 2.7 5.7 40 2.9 60
평균 2.76 5.9 56 2.86 60.2

테스트 결과 분석

code splitting 적용 이후 성능 변화 추이 종합

  • First Contentful Paint (FCP): 3.8s → 2.76s (약 27% 개선)
  • Largest Contentful Paint (LCP): 7.9s → 5.9s (약 25% 개선)
  • Speed Index: 4.0s → 2.86s (약 28% 개선)
  • Performance Score: 56 → 60.2 (약 7.5% 상승)
  • Total Blocking Time (TBT): 44ms → 56ms (Code Splitting 적용 후 소폭 증가)

FCP, LCP, Speed Index 지표는 25~28% 개선되었다. 그러나 TBT가 12ms 증가하였는데, 그 원인은 Code Splitting이 적용되면서 초기 번들 로드 시간은 줄었지만 code splitting을 위해 추가적인 코드 실행이 필요했기 때문으로 추정된다.

Clone this wiki locally