Route-Based Code Splitting Implementation

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Implementing Code Splitting by Routes for Web Apps

Code splitting by routes is the most effective type of bundle splitting. Instead of one monolithic JS file, browser loads only code for current page. Navigating to another route loads corresponding chunk. Result: less traffic, faster first render, better LCP and TTI in Core Web Vitals.

Problem Without Code Splitting

Typical SPA without splitting:

dist/
  assets/
    index-Bx7K9m2p.js   # 1.2 MB — all application code
    vendor-Dq8R3nYk.js  # 800 KB — all dependencies

User opening home page downloads code for checkout page, admin panel, all other sections — even though they don't need them right now.

React Router v6 + React.lazy

// router/index.tsx
import { lazy, Suspense } from 'react'
import { createBrowserRouter, RouterProvider } from 'react-router-dom'
import { AppLayout } from '@/layouts/AppLayout'
import { PageLoader } from '@/components/PageLoader'

// Each route — separate chunk
const Home        = lazy(() => import('@/pages/Home'))
const Catalog     = lazy(() => import('@/pages/Catalog'))
const ProductPage = lazy(() => import('@/pages/ProductPage'))
const Cart        = lazy(() => import('@/pages/Cart'))
const Checkout    = lazy(() => import('@/pages/Checkout'))
const Account     = lazy(() => import('@/pages/Account'))
const AdminDashboard = lazy(() => import('@/pages/admin/Dashboard'))

const router = createBrowserRouter([
  {
    path: '/',
    element: <AppLayout />,
    children: [
      { index: true, element: <Home /> },
      { path: 'catalog',            element: <Catalog /> },
      { path: 'catalog/:id',        element: <ProductPage /> },
      { path: 'cart',               element: <Cart /> },
      { path: 'checkout',           element: <Checkout /> },
      { path: 'account/*',          element: <Account /> },
    ],
  },
  {
    path: '/admin',
    element: <AdminDashboard />,
  },
])

// Suspense wraps RouterProvider — one for entire app
export function App() {
  return (
    <Suspense fallback={<PageLoader />}>
      <RouterProvider router={router} />
    </Suspense>
  )
}

Vite automatically creates separate chunk for each dynamic import:

dist/assets/
  Home-C2mK8pQr.js        # 45 KB
  Catalog-Fp7Xd3nY.js     # 92 KB
  ProductPage-Bv2Rs9mL.js # 67 KB
  Checkout-Dq4Wt1kJ.js    # 180 KB (Stripe, many forms)
  AdminDashboard-Xk9Pn3rT.js # 340 KB (charts, tables)
  vendor-Ym3Cx8wQ.js      # 800 KB (shared dependencies)

Chunk Naming via Magic Comments

const Checkout = lazy(() =>
  import(/* webpackChunkName: "checkout" */ '@/pages/Checkout')
)

// In Vite — via rollupOptions
// vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          // vendor chunks by category
          'vendor-react':  ['react', 'react-dom', 'react-router-dom'],
          'vendor-ui':     ['@radix-ui/react-dialog', '@radix-ui/react-dropdown-menu'],
          'vendor-forms':  ['react-hook-form', 'zod'],
          'vendor-charts': ['recharts'],
        },
      },
    },
  },
})

Next.js App Router

In App Router code splitting works by default: each page.tsx — separate segment. Additionally use dynamic() for heavy components within pages:

// app/catalog/page.tsx
import dynamic from 'next/dynamic'
import { ProductGrid } from '@/components/ProductGrid'

// Filters — heavy, render below fold
const FilterPanel = dynamic(() => import('@/components/FilterPanel'), {
  loading: () => <FilterSkeleton />,
})

// Store map — client-side only
const StoreMap = dynamic(() => import('@/components/StoreMap'), {
  ssr: false,
  loading: () => <div style={{ height: 400 }} className="bg-muted animate-pulse" />,
})

export default function CatalogPage() {
  return (
    <div className="flex gap-8">
      <FilterPanel />
      <main>
        <ProductGrid />
        <StoreMap />
      </main>
    </div>
  )
}

Route Prefetching

Load chunk ahead — before user navigates to link:

// On link hover
import { useEffect } from 'react'

function NavLink({ to, children }: { to: string; children: React.ReactNode }) {
  const prefetch = () => {
    // Dynamically import corresponding chunk
    if (to === '/catalog') import('@/pages/Catalog')
    if (to === '/checkout') import('@/pages/Checkout')
  }

  return (
    <Link to={to} onMouseEnter={prefetch} onFocus={prefetch}>
      {children}
    </Link>
  )
}

In Next.js <Link> does prefetch automatically for visible links in production. Control:

<Link href="/checkout" prefetch={false}>  {/* disable */}
<Link href="/admin" prefetch={true}>       {/* force */}

Loading States and Error Boundaries

// components/PageLoader.tsx
export function PageLoader() {
  return (
    <div className="flex items-center justify-center min-h-[60vh]">
      <div className="flex flex-col items-center gap-4">
        <Spinner size="lg" />
        <p className="text-muted-foreground text-sm">Loading page…</p>
      </div>
    </div>
  )
}
// ErrorBoundary for chunks that failed to load (no network, 404 chunk)
class ChunkErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  state = { hasError: false }

  static getDerivedStateFromError() {
    return { hasError: true }
  }

  handleRetry = () => {
    this.setState({ hasError: false })
    window.location.reload()
  }

  render() {
    if (this.state.hasError) {
      return (
        <div className="text-center py-16">
          <p>Failed to load page</p>
          <button onClick={this.handleRetry}>Refresh</button>
        </div>
      )
    }
    return this.props.children
  }
}

// Usage
<ChunkErrorBoundary>
  <Suspense fallback={<PageLoader />}>
    <RouterProvider router={router} />
  </Suspense>
</ChunkErrorBoundary>

Analyzing Results

# Measure chunk sizes before and after
npx vite build --reporter=verbose

# Source map explorer
npm install --save-dev source-map-explorer
npx source-map-explorer dist/assets/*.js

# Bundle analyzer
npm install --save-dev rollup-plugin-visualizer

Target metrics: initial bundle < 200 KB gzipped, each route chunk < 100 KB gzipped.

Timeline

Setting up code splitting for existing router — 1 day. With bundle analysis, manual vendor chunk splitting, prefetch and error boundary setup — 2–3 days.