JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
PrevNext
performance
mid
bundling

How do you analyze and reduce bundle size?

bundle-analysis
tree-shaking
optimization
webpack
vite
Quick Answer

Use tools like webpack-bundle-analyzer, Vite's rollup-plugin-visualizer, or source-map-explorer to visualize bundle composition. Reduce size by removing unused code, using smaller alternatives, lazy loading, and tree shaking.

Detailed Explanation

Analysis Tools:

  • webpack-bundle-analyzer: Visual treemap
  • rollup-plugin-visualizer: For Vite/Rollup
  • source-map-explorer: From source maps
  • bundlephobia.com: Check package sizes

Common Size Issues:

  • Large dependencies (moment.js, lodash)
  • Unused imports
  • Duplicate dependencies
  • No tree shaking
  • Unoptimized assets

Reduction Strategies:

  1. Replace heavy libraries
  2. Import only what you use
  3. Code splitting
  4. Dynamic imports
  5. Remove dead code
  6. Compress assets

Code Examples

Bundle analysis setup
// vite.config.js with visualizer
import { defineConfig } from 'vite';
import { visualizer } from 'rollup-plugin-visualizer';

export default defineConfig({
  plugins: [
    visualizer({
      filename: 'dist/stats.html',
      open: true,
      gzipSize: true,
      brotliSize: true,
    }),
  ],
});

// webpack.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'bundle-report.html',
    }),
  ],
};

// package.json scripts
{
  "scripts": {
    "analyze": "ANALYZE=true npm run build",
    "analyze:source": "source-map-explorer 'dist/**/*.js'"
  }
}

Resources

Webpack Bundle Analyzer

docs

Bundlephobia

docs

Related Questions

How does code splitting work and when should you use it?

mid
bundling
Previous
How does code splitting work and when should you use it?
Next
What are common React performance optimization techniques?