Build Output Optimization

Analyze bundle size and apply common size-reduction techniques to deliver smaller resources that load faster.

🎯 Introduction

After loading, rendering, and caching, we now return to the source: the build output itself. Every JavaScript and CSS file users download comes from the build tool. How much unused code does it contain? Which dependency takes up the most space? Without answering these questions, optimization becomes guesswork.

By the end of this article, you will be able to:

  • Generate a visual bundle analysis report for a Vite project with rollup-plugin-visualizer.
  • Read the report to identify large modules and bundled dependencies.
  • Apply four common techniques: tree shaking, minification and name mangling, selective imports, and loading dependencies from a CDN.
  • Validate each change with measurements, making one change at a time.

The Webpack course already covers loader and plugin configuration. This article focuses on optimization principles, using Vite for most examples.


🧱 Measure Before Reducing: Bundle Size Analysis

A familiar rule in performance work is no optimization without measurement. Splitting bundles and removing dependencies blindly might save only a few kilobytes while leaving the largest contributors untouched. Always start by finding out what the output contains.

Vite uses Rollup for bundling. rollup-plugin-visualizer generates an HTML report during the build, displaying module sizes as rectangles so you can quickly identify large contributors.

The examples were tested with Node.js v22, Vite 6, and rollup-plugin-visualizer v6. Install the plugin first:

# Local environment: Node.js v22, rollup-plugin-visualizer v6
pnpm add -D rollup-plugin-visualizer

Then register it in vite.config.js:

vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
    plugins: [
        vue(),
        // Generate a bundle analysis report during the build
        visualizer({
            filename: 'dist/report.html', // Report output path
            open: true, // Open the report in a browser after the build
        }),
    ],
});

That is all the configuration needed here. The Vite course explains the configuration basics. Run pnpm run build; after the build, the browser opens report.html automatically:

  • Each rectangle represents a module. Larger rectangles indicate modules that occupy more space in the output.
  • Rectangles are nested by directory. Explore node_modules to inspect the actual contribution of each third-party dependency.
  • The report offers views of gzip and Brotli compressed sizes. Use the gzip view when assessing transfer size to get closer to what users download.

Use the report to answer three questions: Which rectangle is unexpectedly large? Has an entire dependency been bundled? Does the same code appear in multiple chunks? The answers guide your next changes.

The report is for analysis only. Do not deploy dist/report.html with your production site.

✨ Technique 1: Tree Shaking

Tree shaking automatically removes unused code from build output. Like shaking dead branches and leaves from a tree, it keeps the useful parts and discards the rest.

It relies on the static structure of ES modules (ESM). Imports and exports are known before execution, so build tools can analyze which exports are used without running the code and remove unused ones safely. CommonJS require calls execute dynamically at runtime and are harder to analyze this way. This is one reason modern build tools center on ESM.

To make your own code easier to tree-shake, follow two habits:

Habit 1: Prefer named exports over a large default-exported object.

utils.js
// Prefer: export each function separately so unused functions can be omitted
export function formatDate(date) {
    return date.toLocaleDateString();
}

export function formatPrice(num) {
    return num.toFixed(2);
}
// Application code imports only what it uses; formatPrice can be removed
import { formatDate } from './utils';

Habit 2: Avoid top-level side effects. Side effects are actions performed as soon as a module is imported, such as modifying globals, extending prototypes, or sending requests. Build tools cannot safely assume those actions are unnecessary, so they retain them:

bad.js
// Top-level execution: the bundler must retain this even if no export is used
console.log('Module loaded');
window.myLib = { version: '1.0.0' };

export function doSomething() {}

Move initialization into functions that consumers call explicitly to make the module easier to tree-shake.

Tree shaking applies to production builds; development mode retains code for debugging. Verify it using output from pnpm run build, rather than comparing development server sizes.

⚡ Technique 2: Minification, Name Mangling, and Selective Imports

Minification and name mangling remove whitespace and comments, shorten variable names to identifiers such as a and b, and combine redundant code. Production builds in Vite and webpack enable these optimizations by default, so little manual configuration is usually needed.

The technique worth applying yourself is selective importing: if you use only part of a library, bundle only that part.

Component and utility libraries can contribute substantial size. Lodash, for example, provides hundreds of functions, but a project may use only a few. Full-library and selective imports look similar, yet their output sizes can differ greatly:

// Full-library import: the entire lodash library enters the output
import _ from 'lodash';
_.debounce(fn, 300);
// Selective import: bundle only debounce; lodash-es uses ESM and supports tree shaking
import { debounce } from 'lodash-es';
debounce(fn, 300);

The same principle applies to component libraries. Libraries such as Element Plus provide automatic on-demand imports through plugins such as unplugin-vue-components. Only the code and styles for components used in templates are bundled. Their official documentation covers setup; here, remember the principle.

When choosing utility libraries, prefer ESM versions, often marked with an -es suffix, such as lodash-es rather than lodash. ESM enables tree shaking to remove unused parts.

🪤 Technique 3: Loading Dependencies from a CDN

A more aggressive approach is to exclude selected dependencies from the bundle altogether and load them from a public CDN using a <script> tag.

These are called external dependencies. In Vite, configure Rollup's external option:

vite.config.js
export default defineConfig({
    build: {
        rollupOptions: {
            // Exclude lodash-es from the bundle; preserve its import statements
            external: ['lodash-es'],
        },
    },
});

Also load the corresponding global-variable build from the CDN with a script tag in HTML. The library is then absent from your bundle, reducing its size substantially.

Which dependencies suit this approach? Large libraries with stable versions and infrequent updates, such as certain charting libraries or rich text editors. Your output becomes smaller immediately, and public CDN nodes may be closer to users. If a user has visited another site using the same CDN resource, the file may already be cached, making loading almost free.

Consider the costs as well:

  • Availability risk: your features now depend on the third-party CDN remaining available. An outage can break them.
  • Loss of tree shaking: global-variable builds usually contain the whole library, including unused functionality.
  • More complex version management: npm packages and CDN files must be kept in sync manually, making upgrades easier to mishandle.

CDN loading is therefore a tradeoff for selected large, stable dependencies, rather than a default approach. Keep application code and frequently updated frameworks managed by the bundler.


💡 Close the Loop: Measure Every Change

We have covered four techniques, but the workflow matters more: after each optimization, rebuild and inspect the report to confirm that output size actually decreased.

Results often differ from intuition. A dependency you expected to save substantial space may contribute very little. A supposedly selective import may still bundle an entire library because of a configuration error. Without verification, you will miss these issues.

Use this workflow:

  1. Establish a baseline: build before making changes and record the sizes of several large files in the report.
  2. Make one change: apply one optimization at a time, such as selective imports. Combining changes makes it difficult to attribute size differences to a particular cause.
  3. Compare the result: rebuild, confirm that the target rectangle shrank, and record the result.
  4. Check for regressions: verify that functionality still works, for example after switching a dependency to a CDN, before starting the next iteration.

After several iterations, you will understand the composition of your output. This is the basic rhythm of performance work: measure → optimize → measure again.


❓ Questions and Answers

Q1: Is the size shown in the report what users actually download?

Not exactly. The default view shows the raw bundled size, while users typically download gzip- or Brotli-compressed content. The difference can be substantial. Switch to the gzip view for a more realistic loading assessment.

Q2: Why does tree shaking leave unused functions when I use import _ from 'lodash'?

Two factors combine: the default-exported _ object contains all functions, making usage difficult to determine, and lodash uses CommonJS rather than the statically analyzable ESM format. Use named imports from the ESM version, lodash-es.

Q3: Can tree shaking remove code I need?

Pure functional modules are generally safe. Modules with side effects, such as CSS that registers global styles on import or JavaScript that initializes at the top level, need care. Packages commonly declare these in the sideEffects field of package.json. In your own code, move side effects into explicitly called functions where possible.

Q4: Can I combine CDN loading with selective imports?

For a given library, these are alternative approaches: an external CDN library does not participate in bundling, so selective bundling no longer applies. Prefer selective imports when you use only a small portion. Consider CDN loading when you use most of a large, stable library.

Q5: Do these techniques apply to webpack projects?

Yes. Tree shaking, minification, and external dependencies are general bundler concepts. Configuration differs; webpack's externals, for example, is a top-level option. Use webpack-bundle-analyzer for reports, with a similar workflow to visualizer.


🧪 Exercises

Take an existing Vite project, or create one with pnpm create vite, and complete a measure → optimize → validate cycle:

Exercise 1: Install and configure rollup-plugin-visualizer. Run pnpm run build, open the report, and record the three largest modules.

vite.config.js
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
// Write your code here: import visualizer from rollup-plugin-visualizer

export default defineConfig({
    plugins: [
        vue(),
        // Write your code here: register visualizer with open: true
    ],
});

Exercise 2: Install lodash-es v4.x in a Node.js v22 project. Use debounce with a full-library import and then a named import, building after each change. Compare the lodash rectangles to see the effect of selective imports.

// Write your code here: import debounce by name and call it once

const onInput = () => console.log('input');

🎉 You now have the tools to optimize build output! You can analyze bundle size and apply four common reduction techniques. Next, we will use performance metrics to evaluate your improvements with real data.