Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readPerformanceJavaScript

Find heavy dependencies with a Vite treemap

Add rollup-plugin-visualizer to a Vite build, read the treemap, and shrink the biggest rectangle by changing one import.

Your production build works, but the page is slow to load and you suspect the JavaScript bundle is bigger than your app deserves. You have no idea which import is the cause. A treemap shows you in one look.

Draw the treemap

Install rollup-plugin-visualizer with pnpm add -D rollup-plugin-visualizer. Add it to the Vite config and enable gzipSize to compare compressed sizes.

// vite.config.js
import { visualizer } from 'rollup-plugin-visualizer'

export default {
  plugins: [visualizer({ gzipSize: true })],
}

Run pnpm exec vite build. The plugin writes stats.html to your project folder. Open that file in a browser to see the treemap. If you want it to open itself after every build, add open: true to the plugin options.

Read the treemap

The innermost rectangles represent modules. Their areas reflect the selected size metric, with folders or chunks grouping them. Look for the one that is far bigger than the others, and read the path in its label to see which package it comes from.

In a Vite project, install lodash with pnpm add lodash. Reference main.js from index.html with a module script, then put this in main.js. Calling the function keeps it in the build.

import { debounce } from 'lodash'

window.addEventListener('resize', debounce(() => console.log(window.innerWidth), 150))

Build and open stats.html to see how much space lodash.js takes compared with main.js. The Rendered and Gzip buttons at the top switch the areas between the two sizes.

Cut the import

Before I look for a smaller replacement library, I check whether the import path is the problem. Here it is. With the CommonJS Lodash entry point, a named import can still pull in the full module.

Import that function from its own path instead, then build again:

// main.js
import debounce from 'lodash/debounce'

Keep the event listener and rebuild. Look for the separate debounce module and its helpers in the new report, then compare the build’s gzip totals. The sizes depend on the package and bundler versions.

Do the same on your own app. Find the biggest rectangle, check how many of its exports you use, and change the import to the one you need. Build again after each change and compare the chunk size the build prints.