Analyzing and optimizing Vite bundle size
Sometimes when building a JavaScript app with Vite, it complains about bundle size:
Analyzing
Install
rollup-plugin-visualizer
pnpm add rollup-plugin-visualizer
Add
rollup-plugin-visualizer
tovite.config.ts
:import { visualizer } from 'rollup-plugin-visualizer' export default defineConfig({ // ... plugins: [ // ... visualizer(), ], })
Run
pnpm build
and openstats.html
in browser. (Addstats.html
to.gitignore
)
This should show a graph of bundle size. You can see which packages are taking up the most space.
Optimizing
Update vite.config.ts
and add build.rollupOptions.output.manualChunks
:
export default defineConfig({
// ...
build: {
rollupOptions: {
output: {
manualChunks: {
zxing: ['@zxing/browser', '@zxing/library'],
react: ['react', 'react-dom'],
},
},
},
},
})