Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Build and Optimization

Code Splitting and Chunks in Vite

Split your Vite bundle with dynamic import(), control chunks with manualChunks, understand vendor chunks, CSS code splitting and preload hints, and avoid common traps.

A single huge JavaScript file makes every visitor download code for pages they may never open. Code splitting breaks the bundle into smaller chunks that load on demand. Vite and Rollup do much of this automatically; your job is to give them good split points and to tune the rest.

This lesson covers dynamic import(), how Rollup decides chunks, manualChunks, CSS splitting, and the preload hints Vite adds. Config is real and read-only. Two stand-ins in plain JavaScript show lazy loading and how chunk grouping works.

Dynamic import is the split point

A static import is bundled into the importing chunk. A dynamic import() tells the bundler "this module may load later", so it becomes its own chunk:

JavaScript
// real Vite app code, read-only
const button = document.querySelector('#show-chart');

button.addEventListener('click', async () => {
  const { renderChart } = await import('./chart.js'); // separate chunk
  renderChart(document.querySelector('#chart'));
});

The chart library is downloaded only when the button is clicked. In frameworks you usually split by route:

JavaScript
// React (real Vite app code)
import { lazy, Suspense } from 'react';
const Settings = lazy(() => import('./pages/Settings.jsx'));
JavaScript
// Vue Router
{ path: '/settings', component: () => import('./pages/Settings.vue') }

Route-level splitting is the best first step: a visitor to the home page never pays for the settings page.

JS Stand-in: lazy loading a module

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The module ran exactly once even though it was requested twice, just as the browser caches real chunks.

What Rollup does automatically

  • Shared code: if two lazy chunks both import utils.js, Rollup extracts it into a shared chunk instead of duplicating it.
  • Entry chunk: everything reachable only through static imports from main.js.
  • Preloading: Vite rewrites the dynamic import so that a chunk's dependencies are fetched in parallel with <link rel="modulepreload">, avoiding waterfalls (chunk A loads, then discovers it needs B).
  • CSS splitting: CSS imported by an async chunk is extracted into its own .css file and loaded with that chunk. Set build.cssCodeSplit: false to merge all CSS into one file.

Manual chunks

Sometimes you want to control grouping, most commonly to put third-party code into a long-lived vendor chunk. Your own code changes on every deploy, but react changes rarely, so a separate vendor file stays cached:

JavaScript
// vite.config.js (real Vite, read-only)
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules/react') || id.includes('node_modules/react-dom')) {
            return 'react-vendor';
          }
          if (id.includes('node_modules')) return 'vendor';
        },
      },
    },
  },
});

An object form also exists: manualChunks: { react: ['react', 'react-dom'] }.

Do not put everything from node_modules into one vendor chunk without thought. It can force the browser to download libraries a page does not use, and it can create circular chunk imports that break at runtime. Measure before and after, and prefer route splitting.

A stand-in for the grouping function

manualChunks is just a function from a module id to a chunk name. You can test that logic in isolation.

JS Stand-in: assigning modules to chunks

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Naming and sizes

Control file names with output.chunkFileNames, entryFileNames and assetFileNames:

JavaScript
// real Vite
rollupOptions: {
  output: {
    entryFileNames: 'js/[name]-[hash].js',
    chunkFileNames: 'js/[name]-[hash].js',
    assetFileNames: 'assets/[name]-[hash][extname]',
  },
},

Vite warns when a chunk is larger than build.chunkSizeWarningLimit (500 KiB by default, before gzip). Treat the warning as a prompt to look at the bundle (see Bundle Analysis and Performance), not as an error to silence.

Preload and prefetch

When a lazy chunk will almost certainly be needed soon (for example the next page after login), you can hint the browser:

JavaScript
// real Vite app code
import(/* webpackPrefetch: true */ './next-page.js'); // webpack comment: Vite ignores it

Vite does not use magic comments. Instead, trigger the import early yourself, for example on hover:

JavaScript
link.addEventListener('mouseenter', () => import('./pages/Settings.js'), { once: true });

The import resolves into the module cache, and the later click is instant.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What turns a module into a separate chunk?

    A dynamic import() marks a point where the module may load later, so the bundler emits it as its own chunk.
  2. 2. Why create a vendor chunk?

    App code changes on every release while libraries do not, so separating them improves caching.
  3. 3. What does manualChunks return for a module you want Rollup to place automatically?

    Returning undefined leaves the module to Rollup's default chunking.
  4. 4. Where is the best place to start splitting a single-page app?

    Route-level lazy imports give large savings with little complexity.

Summary

  • Dynamic import() creates split points; split by route first.
  • Rollup shares common code, extracts async CSS and Vite adds modulepreload hints.
  • manualChunks groups modules, commonly into vendor chunks; use it sparingly and measure.
  • chunkFileNames and friends control output names.
  • Warm lazy chunks yourself on hover or idle; Vite ignores webpack magic comments.

Next: Build Targets and Browser Support