Skip to content
intermediatePhase 38 · Web Performance

Bundle Optimization

Minimize bundle size with tree shaking, dead code elimination, and analysis.

45m
0 problems
Topic Progress0%

Tree Shaking

Tree Shaking

Remove unused exports from modules.

How Tree Shaking Works

  1. Analyzes import/export statements
  2. Tracks which exports are actually used
  3. Removes unused code from final bundle

Webpack Configuration

// webpack.config.js
module.exports = {
  mode: 'production', // Enables tree shaking
  optimization: {
    usedExports: true, // Mark unused exports
    minimize: true, // Remove dead code
    sideEffects: true, // Check package.json sideEffects
  },
};

Package.json Side Effects

{
  "name": "my-library",
  "sideEffects": [
    "*.css",
    "*.scss",
    "./src/polyfills.js"
  ]
}

ES Modules vs CommonJS

// ✅ Good: ES Modules (tree-shakeable)
import {Button} from './components';
import {formatDate} from './utils';

// ❌ Bad: CommonJS (not tree-shakeable)
const components = require('./components');
const utils = require('./utils');

// ❌ Bad: Importing entire library
import _ from 'lodash';
import {map, filter} from 'lodash';

// ✅ Good: Import specific functions
import map from 'lodash/map';
import filter from 'lodash/filter';

Tree Shaking Example

// utils.js
export const used = () => 'used';
export const unused = () => 'unused';

// app.js
import { used } from './utils';
console.log(used());

// Result: only used() is bundled, unused() is removed

Dead Code Elimination

Dead Code Elimination

Remove code that will never execute.

Dead Code Patterns

// 1. Unreachable code
function example() {
  return;
  console.log('This never runs'); // Dead code
}

// 2. Unused variables
const unused = 'This is never used'; // Dead code

// 3. Unused functions
function unusedFunction() { // Dead code
  return 'never called';
}

// 4. False conditions
if (false) {
  console.log('Never executes'); // Dead code
}

// 5. Console.log in production
console.log('Debug info'); // Should be removed

Terser Configuration

// webpack.config.js
const TerserPlugin = require('terser-webpack-plugin');

module.exports = {
  optimization: {
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true, // Remove console.log
            drop_debugger: true,
            pure_funcs: ['console.log', 'console.info'], // Remove specific functions
          },
          mangle: true,
          output: {
            comments: false, // Remove comments
          },
        },
        extractComments: false,
      }),
    ],
  },
};

Babel Plugin

// babel.config.json
{
  "plugins": [
    ["transform-remove-console", { "exclude": ["error", "warn"] }]
  ]
}

ESLint Rule

// .eslintrc.json
{
  "rules": {
    "no-unused-vars": "error",
    "no-unreachable": "error",
    "no-console": ["warn", { "allow": ["warn", "error"] }]
  }
}

Bundle Analysis

Bundle Analysis

Visualize and optimize bundle contents.

Webpack Bundle Analyzer

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

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

// Run analysis
npm run build -- --analyze

Source Map Explorer

// package.json
{
  "scripts": {
    "analyze": "source-map-explorer 'dist/*.js'"
  }
}

// Build with source maps
GENERATE_SOURCEMAP=true npm run build

Bundlephobia

# Check package sizes
npx bundlephobia lodash
npx bundlephobia moment

Size Budgets

// package.json
{
  "budgets": [
    {
      "type": "initial",
      "maximumWarning": "250kb",
      "maximumError": "350kb"
    },
    {
      "type": "lazy",
      "maximumWarning": "50kb",
      "maximumError": "100kb"
    }
  ]
}

Analysis Checklist

  • Check for large dependencies
  • Identify duplicate packages
  • Find unused imports
  • Look for large individual modules
  • Check chunk sizes
  • Verify tree shaking is working

Optimization Strategies

  1. Replace large libraries with smaller alternatives
  2. Import only needed functions from large libraries
  3. Use dynamic imports for code splitting
  4. Remove unused dependencies
  5. Upgrade dependencies for smaller bundles

Practice Problems

0/3solved
Build Bundle Optimization Component

Create a reusable React component implementing Bundle Optimization. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Bundle Optimization Testing

Write unit and integration tests for Bundle Optimization using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Bundle Optimization Performance

Optimize Bundle Optimization for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What is tree shaking?

Question 1 options

2. Why are ES Modules better for tree shaking?

Question 2 options

3. What is the primary purpose of Bundle Optimization?

Question 3 options

4. What is a common mistake when implementing Bundle Optimization?

Question 4 options

Flashcards

Question

What is tree shaking?

Answer

A build process that removes unused JavaScript exports from the final bundle.

Question

Why use named exports over default exports?

Answer

Named exports are easier to tree-shake than default exports.

Question

What is webpack-bundle-analyzer?

Answer

A tool that visualizes bundle contents to identify optimization opportunities.

Question

How do you reduce bundle size?

Answer

Tree shake, code split, import specific functions, and remove unused dependencies.

Question

What is Bundle Optimization?

Answer

Bundle Optimization is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.Tree shaking removes unused JavaScript exports
  • 2.ES Modules enable better tree shaking than CommonJS
  • 3.Use bundle analyzers to identify optimization opportunities
  • 4.Remove console.log and debugger in production
  • 5.Import specific functions from large libraries

Interview Tips

  • Explain how tree shaking works
  • Discuss strategies for reducing bundle size
  • Know how to analyze and optimize bundles

Cheat Sheet

Bundle Optimization Cheat Sheet

Tree Shaking

  • Use ES Modules (import/export)
  • Enable usedExports: true
  • Set sideEffects in package.json

Dead Code Elimination

  • Remove console.log in production
  • Drop debugger statements
  • Use Terser compression

Bundle Analysis

  • webpack-bundle-analyzer
  • source-map-explorer
  • bundlephobia

Quick Wins

  • Import specific functions from large libs
  • Replace moment with date-fns
  • Replace lodash with lodash-es