Vite

Auditing Vite bundle size and tree shaking

Generate a Vite bundle treemap, compare raw and compressed size, and diagnose CommonJS, module side effects, and heavy barrel imports.

Auditing Vite bundle size and tree shaking

A bundle treemap can show whether a large file comes from one dependency or many legitimate imports. I use rollup-plugin-visualizer to identify which modules reached the production bundle and measure whether a smaller import actually removed code.

Choose a size metric before comparing

  • Stat size describes the original input attributed to a module.
  • Parsed size approximates the emitted code before transfer compression. It helps explain why a small Gzip payload can still leave the browser with considerable parsing work.
  • Gzip and Brotli size estimate transfer bytes after compression. Measure actual network delivery when response encodings and caches matter.

I compare the same metric across equivalent builds. A treemap helps me ask which entry or route brought a heavyweight module into the graph. A difference in compressed bytes alone does not prove how the browser will execute the code.

flowchart TD
    A["Run pnpm build:analyze"] --> B["Generate dist/stats.html"]
    B --> C{"Which module is large?"}
    C -->|"CommonJS package"| D["Consider an ESM distribution"]
    C -->|"Unknown side effects"| E["Declare side effects accurately"]
    C -->|"Large barrel export"| F["Try a supported subpath import"]
    D --> G["Rebuild and inspect included modules"]
    E --> G
    F --> G
    G --> H["Measure the resulting chunk size"]

Create an on-demand report

1
2
# Install the plugin
pnpm add -D rollup-plugin-visualizer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// vite.config.ts
import { defineConfig, type PluginOption } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig(({ mode }) => {
  const isAnalyze = mode === 'analyze' || process.env.ANALYZE === 'true';

  const plugins: PluginOption[] = [react()];

  if (isAnalyze) {
    plugins.push(
      visualizer({
        filename: './dist/stats.html', // Report output path
        open: false,                   // Keep the browser closed after the build
        gzipSize: true,                // Estimate transfer size with Gzip
        brotliSize: true,              // Estimate transfer size with Brotli
        template: 'treemap',           // 'treemap' | 'sunburst' | 'network'
        title: 'Production bundle analysis',
      }) as PluginOption
    );
  }

  return {
    plugins,
    build: {
      sourcemap: isAnalyze, // Enable source maps for analysis
    },
  };
});
1
2
3
4
5
6
7
8
9
// package.json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "build:analyze": "vite build --mode analyze",
    "preview": "vite preview"
  }
}

This configuration uses an analyze mode to produce dist/stats.html with source maps. Normal builds avoid generating the report. An analysis report can contain internal package and source information, so I keep it with investigation artifacts. A CI job can enforce a public bundle budget separately from deciding who can access private analysis outputs.

Look for CommonJS imports that retain unused exports

ESM imports expose a static dependency graph. A bundler can track used exports and remove unused code when the surrounding behavior permits it. CommonJS can alter exported properties at runtime. Its interop wrappers and module structure can make precise analysis harder. Inspect the actual output because the result depends on the package and bundler.

1
2
3
// Import from the CommonJS-based lodash package
import { cloneDeep } from 'lodash'; 
// Example build includes 250 kB or more from lodash
1
2
3
// Import from the ESM distribution
import { cloneDeep } from 'lodash-es';
// Example build retains cloneDeep and its dependencies (18 kB)

The sample changes from lodash to lodash-es to give the bundler an ESM representation of the desired function. Before replacing a dependency in production, compare the behavior of the actual imported functions and test the consumer cases as well as the bundle size.

Check side effects and barrel imports

Top-level module code can register a plugin or import CSS for its effect. Only set sideEffects: false when dropping an unused module preserves behavior. Otherwise list the effectful files explicitly.

1
2
3
4
5
6
// packages/ui-components/package.json
{
  "name": "@my-org/ui-components",
  "version": "1.0.0",
  "sideEffects": false
}
1
2
3
4
5
6
{
  "sideEffects": [
    "*.css",
    "*.scss"
  ]
}

A barrel that re-exports dozens of modules is convenient and can still shake correctly when the graph is clean. Circular dependencies or a re-export with top-level initialization can cause more modules to survive. A supported direct import of a rarely used heavy component makes its ownership clearer. Check the package exports rather than relying on a private file path.

Measure the result of the import change

Bundle analysis output identifying a large lodash vendor contribution Figure 1. The example report identifies the lodash contribution as a candidate for analysis.

Build comparison after switching lodash imports to lodash-es Figure 2. The same use case retains a much smaller module contribution after switching distributions.

BuildEmitted sizeGzip
CommonJS lodash254.10 kB24.15 kB
ESM lodash-es18.42 kB4.80 kB
Reduction235.68 kB (92.7%)19.35 kB

These numbers describe the affected output in the example. They do not imply that every CommonJS or lodash import will see the same change. I verify the target route’s request list because moving code to another shared file can make one reported chunk smaller without reducing the work done by that route.

Keep measurement part of dependency changes

  • Compare raw, Gzip, and Brotli sizes against the same previous build.
  • Confirm the expected modules disappeared rather than moving to a different initial chunk.
  • Exercise CSS, registration code, and other side effects after changing package metadata.
  • Use asset precompression to reduce transfer bytes after removing code that should never have reached the bundle.
📈⚖️ Visuallize your bundle. Contribute to btd/rollup-plugin-visualizer development by creating an account on GitHub.
This post is licensed under CC BY 4.0 by the author.