CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack

A comprehensive module bundler and build tool for JavaScript applications with advanced optimization and plugin system.

Pending
Overview
Eval results
Files

optimization.mddocs/

Optimization System

Webpack's optimization system provides comprehensive tools for improving bundle size, runtime performance, and caching effectiveness. It includes automatic code splitting, tree shaking, module concatenation, content hashing, and advanced optimization strategies for both development and production environments.

Capabilities

OptimizationOptions Interface

The main optimization configuration interface controlling all optimization behaviors.

interface OptimizationOptions {
  /** Enable/disable minimization */
  minimize?: boolean;
  
  /** Minimizer plugins to use */
  minimizer?: WebpackPluginInstance[];
  
  /** Split chunks configuration */
  splitChunks?: SplitChunksOptions | false;
  
  /** Runtime chunk extraction */
  runtimeChunk?: RuntimeChunkOptions;
  
  /** Emit assets even with errors */
  emitOnErrors?: boolean;
  
  /** Module concatenation (scope hoisting) */
  concatenateModules?: boolean;
  
  /** Side effects detection mode */
  sideEffects?: boolean | "flag";
  
  /** Used exports detection (tree shaking) */
  usedExports?: boolean | "global";
  
  /** Provided exports detection */
  providedExports?: boolean;
  
  /** Flag included chunks optimization */
  flagIncludedChunks?: boolean;
  
  /** Module ID optimization strategy */
  moduleIds?: ModuleIdsType;
  
  /** Chunk ID optimization strategy */
  chunkIds?: ChunkIdsType;
  
  /** Remove available modules optimization */
  removeAvailableModules?: boolean;
  
  /** Remove empty chunks */
  removeEmptyChunks?: boolean;
  
  /** Merge duplicate chunks */
  mergeDuplicateChunks?: boolean;
  
  /** Mangle WASM imports */
  mangleWasmImports?: boolean;
  
  /** Portable records */
  portableRecords?: boolean;
  
  /** Real content hash generation */
  realContentHash?: boolean;
  
  /** Inner graph optimization */
  innerGraph?: boolean;
  
  /** Mangle exports */
  mangleExports?: boolean | "deterministic" | "size";
  
  /** Node.js environment detection */
  nodeEnv?: string | false;
  
  /** Check WASM types */
  checkWasmTypes?: boolean;
}

/** Module ID optimization types */
type ModuleIdsType = "natural" | "named" | "deterministic" | "hashed" | "size" | false;

/** Chunk ID optimization types */  
type ChunkIdsType = "natural" | "named" | "deterministic" | "size" | "total-size" | false;

Usage Examples:

module.exports = {
  optimization: {
    // Production optimizations
    minimize: true,
    moduleIds: "deterministic",
    chunkIds: "deterministic",
    
    // Tree shaking
    usedExports: true,
    sideEffects: false,
    
    // Advanced optimizations
    concatenateModules: true,
    innerGraph: true,
    realContentHash: true,
    
    // Code splitting
    splitChunks: {
      chunks: "all",
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all"
        }
      }
    },
    
    // Runtime extraction
    runtimeChunk: "single"
  }
};

SplitChunksPlugin

Automatically splits code into separate chunks for optimal loading and caching.

class SplitChunksPlugin {
  /**
   * Creates new SplitChunksPlugin instance
   * @param options - Split chunks configuration options
   */
  constructor(options?: SplitChunksOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface SplitChunksOptions {
  /** Which chunks to optimize */
  chunks?: ChunksFilterType;
  
  /** Minimum size before chunk is split */
  minSize?: number;
  
  /** Minimum size reduction required */
  minSizeReduction?: number;
  
  /** Minimum remaining size after split */
  minRemainingSize?: number;
  
  /** Maximum size hint for chunks */
  maxSize?: number;
  
  /** Maximum size for async chunks */
  maxAsyncSize?: number;
  
  /** Maximum size for initial chunks */
  maxInitialSize?: number;
  
  /** Maximum number of async requests */
  maxAsyncRequests?: number;
  
  /** Maximum number of initial requests */
  maxInitialRequests?: number;
  
  /** Size threshold for enforcing split */
  enforceSizeThreshold?: number;
  
  /** Delimiter for automatic naming */
  automaticNameDelimiter?: string;
  
  /** Cache groups configuration */
  cacheGroups?: CacheGroupsOptions;
  
  /** Default chunk name */
  name?: string | false | SplitChunksNameFunction;
  
  /** Chunk filename template */
  filename?: string | SplitChunksFilenameFunction;
  
  /** Hide path info in names */
  hidePathInfo?: boolean;
  
  /** Use used exports info */
  usedExports?: boolean;
}

/** Chunks filter types */
type ChunksFilterType = 
  | "all" 
  | "async" 
  | "initial" 
  | ((chunk: Chunk) => boolean);

/** Cache groups configuration */
interface CacheGroupsOptions {
  [key: string]: CacheGroup | false;
}

interface CacheGroup {
  /** Test condition for modules */
  test?: TestCondition;
  
  /** Include condition for modules */
  include?: TestCondition;
  
  /** Exclude condition for modules */
  exclude?: TestCondition;
  
  /** Priority for cache group */
  priority?: number;
  
  /** Minimum chunks that must share module */
  minChunks?: number;
  
  /** Minimum size for cache group */
  minSize?: number;
  
  /** Maximum size for cache group */
  maxSize?: number;
  
  /** Minimum size reduction */
  minSizeReduction?: number;
  
  /** Maximum async size */
  maxAsyncSize?: number;
  
  /** Maximum initial size */
  maxInitialSize?: number;
  
  /** Enforce size threshold */
  enforceSizeThreshold?: number;
  
  /** Reuse existing chunk if possible */
  reuseExistingChunk?: boolean;
  
  /** Cache group name */
  name?: string | false | ((module: Module, chunks: Chunk[], key: string) => string);
  
  /** Filename template */
  filename?: string | ((pathData: PathData) => string);
  
  /** Chunks to include */
  chunks?: ChunksFilterType;
  
  /** Automatic name delimiter */
  automaticNameDelimiter?: string;
  
  /** Use used exports */
  usedExports?: boolean;
  
  /** ID hint for deterministic naming */
  idHint?: string;
}

/** Test condition types */
type TestCondition = string | RegExp | ((module: Module) => boolean);

/** Split chunks name function */
type SplitChunksNameFunction = (
  module?: Module,
  chunks?: Chunk[],
  cacheGroupKey?: string
) => string | undefined;

/** Split chunks filename function */  
type SplitChunksFilenameFunction = (pathData: PathData) => string;

Usage Examples:

module.exports = {
  optimization: {
    splitChunks: {
      // Split all chunks including async and initial
      chunks: "all",
      
      // Minimum size before creating chunk (20KB)
      minSize: 20000,
      
      // Maximum size hint (244KB)
      maxSize: 244000,
      
      // Cache groups for different chunk types
      cacheGroups: {
        // Vendor libraries
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          priority: 10,
          chunks: "all",
          reuseExistingChunk: true
        },
        
        // React ecosystem
        react: {
          test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
          name: "react",
          priority: 20,
          chunks: "all"
        },
        
        // Common modules shared between entry points
        common: {
          name: "common",
          minChunks: 2,
          priority: 5,
          chunks: "all",
          reuseExistingChunk: true,
          enforce: true
        },
        
        // Utility libraries
        utils: {
          test: /[\\/]src[\\/]utils[\\/]/,
          name: "utils",
          priority: 15,
          chunks: "all"
        },
        
        // CSS chunks
        styles: {
          name: "styles",
          test: /\.(css|scss|sass)$/,
          chunks: "all",
          priority: 1
        }
      }
    }
  }
};

// Advanced configuration with dynamic naming
module.exports = {
  optimization: {
    splitChunks: {
      chunks: "all",
      minSize: 10000,
      maxSize: 200000,
      
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module, chunks, cacheGroupKey) {
            const moduleFileName = module
              .identifier()
              .split("/")
              .reduceRight((item) => item);
            const allChunksNames = chunks.map((item) => item.name).join("~");
            return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
          },
          chunks: "all"
        }
      }
    }
  }
};

RuntimeChunkPlugin

Extracts webpack runtime code into separate chunks for better caching.

class RuntimeChunkPlugin {
  /**
   * Creates new RuntimeChunkPlugin instance
   * @param options - Runtime chunk options
   */
  constructor(options?: RuntimeChunkPluginOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface RuntimeChunkPluginOptions {
  /** Runtime chunk name or function */
  name?: string | RuntimeChunkFunction;
}

/** Runtime chunk configuration types */
type RuntimeChunkOptions = 
  | "single" 
  | "multiple" 
  | boolean
  | { name?: string | RuntimeChunkFunction };

/** Runtime chunk name function */
type RuntimeChunkFunction = (entrypoint: Entrypoint) => string;

Usage Examples:

module.exports = {
  optimization: {
    // Single runtime chunk for all entry points
    runtimeChunk: "single"
  }
};

// Multiple runtime chunks (one per entry)
module.exports = {
  optimization: {
    runtimeChunk: "multiple"
  }
};

// Custom runtime chunk naming
module.exports = {
  optimization: {
    runtimeChunk: {
      name: (entrypoint) => `runtime-${entrypoint.name}`
    }
  }
};

// Using plugin directly
module.exports = {
  plugins: [
    new webpack.optimize.RuntimeChunkPlugin({
      name: "manifest"
    })
  ]
};

ModuleConcatenationPlugin

Enables scope hoisting by concatenating modules into single scopes when possible.

class ModuleConcatenationPlugin {
  /**
   * Creates new ModuleConcatenationPlugin instance
   */
  constructor();
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

Usage Examples:

module.exports = {
  optimization: {
    // Enable module concatenation (scope hoisting)
    concatenateModules: true
  }
};

// Using plugin directly
module.exports = {
  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin()
  ]
};

// Production mode enables this automatically
module.exports = {
  mode: "production" // Includes concatenateModules: true
};

RealContentHashPlugin

Generates content-based hashes after optimization for accurate cache invalidation.

class RealContentHashPlugin {
  /**
   * Creates new RealContentHashPlugin instance
   * @param options - Real content hash options
   */
  constructor(options?: RealContentHashPluginOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface RealContentHashPluginOptions {
  /** Hash function to use */
  hashFunction?: string;
  
  /** Hash digest encoding */
  hashDigest?: string;
}

Usage Examples:

module.exports = {
  optimization: {
    // Enable real content hash
    realContentHash: true
  }
};

// Using plugin directly with custom options
module.exports = {
  plugins: [
    new webpack.optimize.RealContentHashPlugin({
      hashFunction: "sha256",
      hashDigest: "hex"
    })
  ]
};

// Combine with content hash in output
module.exports = {
  output: {
    filename: "[name].[contenthash].js",
    chunkFilename: "[name].[contenthash].chunk.js"
  },
  optimization: {
    realContentHash: true
  }
};

AggressiveMergingPlugin

Merges chunks aggressively to reduce the number of requests.

class AggressiveMergingPlugin {
  /**
   * Creates new AggressiveMergingPlugin instance  
   * @param options - Aggressive merging options
   */
  constructor(options?: AggressiveMergingPluginOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface AggressiveMergingPluginOptions {
  /** Minimum size reduction required for merge */
  minSizeReduce?: number;
  
  /** Move modules to parents */
  moveToParents?: boolean;
}

Usage Examples:

module.exports = {
  plugins: [
    new webpack.optimize.AggressiveMergingPlugin({
      minSizeReduce: 1.5,
      moveToParents: true
    })
  ]
};

// Combine with other chunk optimizations
module.exports = {
  optimization: {
    splitChunks: {
      chunks: "all",
      maxInitialRequests: 3,
      maxAsyncRequests: 5
    }
  },
  plugins: [
    new webpack.optimize.AggressiveMergingPlugin()
  ]
};

LimitChunkCountPlugin

Controls the maximum number of chunks to prevent too many HTTP requests.

class LimitChunkCountPlugin {
  /**
   * Creates new LimitChunkCountPlugin instance
   * @param options - Chunk count limit options
   */
  constructor(options?: LimitChunkCountPluginOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface LimitChunkCountPluginOptions {
  /** Maximum number of chunks */
  maxChunks: number;
}

Usage Examples:

module.exports = {
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 5
    })
  ]
};

// For HTTP/1.1 environments with request limits
module.exports = {
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 1 // Bundle everything into single chunk
    })
  ]
};

// Balance between caching and request count
module.exports = {
  optimization: {
    splitChunks: {
      chunks: "all"
    }
  },
  plugins: [
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 10
    })
  ]
};

MinChunkSizePlugin

Ensures chunks meet minimum size requirements by merging small chunks.

class MinChunkSizePlugin {
  /**
   * Creates new MinChunkSizePlugin instance
   * @param options - Minimum chunk size options
   */
  constructor(options?: MinChunkSizePluginOptions);
  
  /**
   * Apply plugin to compiler
   * @param compiler - Webpack compiler instance
   */
  apply(compiler: Compiler): void;
}

interface MinChunkSizePluginOptions {
  /** Minimum chunk size in bytes */
  minChunkSize: number;
}

Usage Examples:

module.exports = {
  plugins: [
    new webpack.optimize.MinChunkSizePlugin({
      minChunkSize: 10000 // 10KB minimum
    })
  ]
};

// Prevent tiny chunks from code splitting
module.exports = {
  optimization: {
    splitChunks: {
      chunks: "all",
      minSize: 20000
    }
  },
  plugins: [
    new webpack.optimize.MinChunkSizePlugin({
      minChunkSize: 15000
    })
  ]
};

Tree Shaking and Dead Code Elimination

Webpack's tree shaking capabilities remove unused exports and dead code for smaller bundles.

Used Exports Detection

interface UsedExportsOptions {
  /** Enable used exports detection */
  usedExports?: boolean | "global";
  
  /** Side effects detection */
  sideEffects?: boolean | "flag" | string[] | ((request: string) => boolean);
  
  /** Provided exports detection */
  providedExports?: boolean;
}

Usage Examples:

module.exports = {
  mode: "production", // Enables tree shaking by default
  
  optimization: {
    // Enable used exports detection
    usedExports: true,
    
    // Mark as side-effect free for better tree shaking
    sideEffects: false,
    
    // Detect provided exports
    providedExports: true
  }
};

// Package.json side effects configuration
{
  "sideEffects": false // Mark entire package as side-effect free
}

// Or specify files with side effects
{
  "sideEffects": [
    "./src/polyfills.js",
    "*.css"
  ]
}

// Module-level side effects configuration
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        sideEffects: false // Mark JavaScript files as side-effect free
      },
      {
        test: /\.css$/,
        sideEffects: true // CSS imports have side effects
      }
    ]
  }
};

Inner Graph Optimization

Advanced optimization analyzing module internals for better tree shaking.

interface InnerGraphOptions {
  /** Enable inner graph optimization */
  innerGraph?: boolean;
}

Usage Examples:

module.exports = {
  optimization: {
    // Enable advanced tree shaking
    innerGraph: true,
    usedExports: true,
    sideEffects: false
  }
};

// Production mode enables this automatically
module.exports = {
  mode: "production"
};

Module and Chunk ID Optimization

Optimization strategies for module and chunk identifiers affecting caching and bundle size.

Module ID Strategies

interface ModuleIdOptions {
  /** Module ID generation strategy */
  moduleIds?: ModuleIdsType;
}

type ModuleIdsType = 
  | "natural"       // Natural numbers in order
  | "named"         // Human readable names (development)
  | "deterministic" // Deterministic short hashes (production)
  | "hashed"        // Full content hashes
  | "size"          // Sort by module size
  | false;          // No optimization

Usage Examples:

module.exports = {
  optimization: {
    // Development: readable names for debugging
    moduleIds: process.env.NODE_ENV === "development" ? "named" : "deterministic"
  }
};

// Production: deterministic IDs for caching
module.exports = {
  mode: "production",
  optimization: {
    moduleIds: "deterministic",
    chunkIds: "deterministic"
  }
};

Chunk ID Strategies

interface ChunkIdOptions {
  /** Chunk ID generation strategy */
  chunkIds?: ChunkIdsType;
}

type ChunkIdsType = 
  | "natural"       // Natural numbers
  | "named"         // Human readable names
  | "deterministic" // Deterministic short hashes
  | "size"          // Sort by chunk size
  | "total-size"    // Sort by total size including dependencies
  | false;          // No optimization

Usage Examples:

module.exports = {
  optimization: {
    chunkIds: "deterministic"
  }
};

// Size-based optimization for loading priority
module.exports = {
  optimization: {
    chunkIds: "total-size" // Load smaller chunks first
  }
};

ID Optimization Plugins

Direct plugin usage for advanced ID optimization scenarios.

class DeterministicChunkIdsPlugin {
  /**
   * Creates deterministic chunk IDs plugin
   * @param options - Plugin options
   */
  constructor(options?: DeterministicIdsPluginOptions);
  
  apply(compiler: Compiler): void;
}

class DeterministicModuleIdsPlugin {
  /**
   * Creates deterministic module IDs plugin
   * @param options - Plugin options
   */
  constructor(options?: DeterministicIdsPluginOptions);
  
  apply(compiler: Compiler): void;
}

class NamedChunkIdsPlugin {
  /**
   * Creates named chunk IDs plugin for development
   */
  constructor();
  
  apply(compiler: Compiler): void;
}

class NamedModuleIdsPlugin {
  /**
   * Creates named module IDs plugin for development
   */
  constructor();
  
  apply(compiler: Compiler): void;
}

class HashedModuleIdsPlugin {
  /**
   * Creates hashed module IDs plugin
   * @param options - Hashing options
   */
  constructor(options?: HashedModuleIdsPluginOptions);
  
  apply(compiler: Compiler): void;
}

interface DeterministicIdsPluginOptions {
  /** Maximum ID length */
  maxLength?: number;
  
  /** Salt for hash generation */
  salt?: string;
  
  /** Context for relative paths */
  context?: string;
}

interface HashedModuleIdsPluginOptions {
  /** Hash function */
  hashFunction?: string;
  
  /** Hash digest */
  hashDigest?: string;
  
  /** Hash digest length */
  hashDigestLength?: number;
}

Usage Examples:

// Custom deterministic IDs with max length
module.exports = {
  plugins: [
    new webpack.ids.DeterministicChunkIdsPlugin({
      maxLength: 5,
      salt: "my-app"
    }),
    new webpack.ids.DeterministicModuleIdsPlugin({
      maxLength: 10
    })
  ]
};

// Development-friendly named IDs
module.exports = {
  plugins: [
    new webpack.ids.NamedChunkIdsPlugin(),
    new webpack.ids.NamedModuleIdsPlugin()
  ]
};

// Content-based hashed IDs
module.exports = {
  plugins: [
    new webpack.ids.HashedModuleIdsPlugin({
      hashFunction: "sha256",
      hashDigest: "base64",
      hashDigestLength: 8
    })
  ]
};

Minimization and Compression

Code minimization and compression strategies for production builds.

Minimization Configuration

interface MinimizationOptions {
  /** Enable/disable minimization */
  minimize?: boolean;
  
  /** Array of minimizer plugins */
  minimizer?: WebpackPluginInstance[];
}

Usage Examples:

const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  optimization: {
    minimize: true,
    minimizer: [
      // JavaScript minimization
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true,
            pure_funcs: ["console.log", "console.info"]
          },
          mangle: {
            safari10: true
          },
          output: {
            comments: false,
            ascii_only: true
          }
        },
        extractComments: false,
        parallel: true
      }),
      
      // CSS minimization
      new CssMinimizerPlugin({
        minimizerOptions: {
          preset: [
            "default",
            {
              discardComments: { removeAll: true },
              normalizeWhitespace: true
            }
          ]
        }
      })
    ]
  }
};

// Development minimization for testing
module.exports = {
  optimization: {
    minimize: process.env.NODE_ENV === "production",
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: false,
          mangle: false,
          keep_fnames: true,
          keep_classnames: true
        }
      })
    ]
  }
};

Side Effects Handling

Proper side effects configuration for effective tree shaking.

Side Effects Configuration

interface SideEffectsOptions {
  /** Side effects detection mode */
  sideEffects?: boolean | "flag" | string[] | SideEffectsFunction;
}

type SideEffectsFunction = (request: string, context: string) => boolean;

Usage Examples:

module.exports = {
  optimization: {
    sideEffects: false // Mark all modules as side-effect free
  }
};

// Conditional side effects
module.exports = {
  optimization: {
    sideEffects: (request) => {
      // CSS and polyfills have side effects
      return /\.(css|scss|sass)$/.test(request) || 
             request.includes("polyfill");
    }
  }
};

// Array of side effect patterns
module.exports = {
  optimization: {
    sideEffects: [
      "*.css",
      "*.scss", 
      "./src/polyfills.js",
      "@babel/polyfill"
    ]
  }
};

// Module rule-level side effects
module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: "babel-loader",
        sideEffects: false
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
        sideEffects: true
      }
    ]
  }
};

Performance Optimization Strategies

Development Optimization

Configuration optimized for fast development builds and debugging.

module.exports = {
  mode: "development",
  
  optimization: {
    // Disable optimization for faster builds
    minimize: false,
    
    // Simple module/chunk IDs for debugging
    moduleIds: "named",
    chunkIds: "named",
    
    // Basic code splitting for development
    splitChunks: {
      chunks: "async",
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          chunks: "all",
          priority: 10
        }
      }
    },
    
    // Separate runtime for HMR
    runtimeChunk: "single",
    
    // Remove available modules for faster rebuilds
    removeAvailableModules: false,
    
    // Don't remove empty chunks for debugging
    removeEmptyChunks: false,
    
    // Keep used exports info for tree shaking preview
    usedExports: true,
    sideEffects: false,
    
    // Enable provided exports for better IntelliSense
    providedExports: true
  },
  
  // Fast source maps for development
  devtool: "eval-cheap-module-source-map"
};

Production Optimization

Configuration optimized for production bundle size and runtime performance.

const TerserPlugin = require("terser-webpack-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const CompressionPlugin = require("compression-webpack-plugin");

module.exports = {
  mode: "production",
  
  optimization: {
    // Full minimization
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true,
            drop_debugger: true,
            passes: 2,
            pure_funcs: ["console.log", "console.info", "console.debug"]
          },
          mangle: {
            safari10: true,
            properties: {
              regex: /^_/
            }
          }
        },
        parallel: true,
        extractComments: false
      }),
      new CssMinimizerPlugin()
    ],
    
    // Aggressive code splitting
    splitChunks: {
      chunks: "all",
      minSize: 20000,
      maxSize: 200000,
      minSizeReduction: 10000,
      maxAsyncRequests: 30,
      maxInitialRequests: 30,
      
      cacheGroups: {
        // Framework code
        framework: {
          test: /[\\/]node_modules[\\/](react|react-dom|vue|angular)[\\/]/,
          name: "framework",
          priority: 40,
          chunks: "all"
        },
        
        // Vendor libraries
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          priority: 20,
          chunks: "all",
          reuseExistingChunk: true
        },
        
        // Common code
        common: {
          name: "common",
          minChunks: 2,
          priority: 10,
          chunks: "all",
          reuseExistingChunk: true
        }
      }
    },
    
    // Runtime extraction
    runtimeChunk: "single",
    
    // Deterministic IDs for caching
    moduleIds: "deterministic",
    chunkIds: "deterministic",
    
    // Tree shaking
    usedExports: true,
    sideEffects: false,
    providedExports: true,
    
    // Advanced optimizations
    concatenateModules: true,
    innerGraph: true,
    realContentHash: true,
    mangleExports: "deterministic",
    
    // Remove optimizations
    removeAvailableModules: true,
    removeEmptyChunks: true,
    mergeDuplicateChunks: true,
    
    // Flag optimizations
    flagIncludedChunks: true
  },
  
  plugins: [
    // Gzip compression
    new CompressionPlugin({
      algorithm: "gzip",
      test: /\.(js|css|html|svg)$/,
      threshold: 8192,
      minRatio: 0.8
    }),
    
    // Brotli compression
    new CompressionPlugin({
      filename: "[path][base].br",
      algorithm: "brotliCompress",
      test: /\.(js|css|html|svg)$/,
      compressionOptions: {
        level: 11
      },
      threshold: 8192,
      minRatio: 0.8
    }),
    
    // Additional chunk optimization
    new webpack.optimize.LimitChunkCountPlugin({
      maxChunks: 10
    }),
    
    new webpack.optimize.MinChunkSizePlugin({
      minChunkSize: 30000
    })
  ]
};

Library Optimization

Optimizations specific to library builds.

module.exports = {
  mode: "production",
  
  optimization: {
    minimize: true,
    
    // Don't split chunks for libraries
    splitChunks: {
      chunks: () => false
    },
    
    // No runtime chunk for libraries
    runtimeChunk: false,
    
    // Deterministic IDs for consistent builds
    moduleIds: "deterministic",
    
    // Tree shaking for library exports
    usedExports: true,
    sideEffects: false,
    
    // Module concatenation for smaller bundles
    concatenateModules: true
  },
  
  // Externalize dependencies
  externals: {
    react: {
      commonjs: "react",
      commonjs2: "react",
      amd: "React",
      root: "React"
    },
    "react-dom": {
      commonjs: "react-dom",
      commonjs2: "react-dom",
      amd: "ReactDOM", 
      root: "ReactDOM"
    }
  },
  
  output: {
    library: {
      name: "MyLibrary",
      type: "umd"
    },
    globalObject: "this"
  }
};

Micro-frontend Optimization

Optimizations for micro-frontend architectures with shared dependencies.

const ModuleFederationPlugin = require("@module-federation/webpack");

module.exports = {
  mode: "production",
  
  optimization: {
    // Standard production optimizations
    minimize: true,
    splitChunks: {
      chunks: "async", // Don't split shared chunks
      cacheGroups: {
        vendor: false, // Disable vendor splitting for federation
        default: false
      }
    },
    
    // Deterministic IDs for consistency across micro-frontends
    moduleIds: "deterministic",
    chunkIds: "deterministic"
  },
  
  plugins: [
    new ModuleFederationPlugin({
      name: "shell",
      filename: "remoteEntry.js",
      
      // Shared dependencies
      shared: {
        react: {
          singleton: true,
          eager: true,
          requiredVersion: "^17.0.0"
        },
        "react-dom": {
          singleton: true,
          eager: true,
          requiredVersion: "^17.0.0"
        }
      }
    })
  ]
};

Bundle Analysis and Optimization

Tools and techniques for analyzing and optimizing webpack bundles.

Bundle Analysis Configuration

const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    // Bundle size analysis
    new BundleAnalyzerPlugin({
      analyzerMode: process.env.ANALYZE ? "server" : "disabled",
      openAnalyzer: false,
      generateStatsFile: true,
      statsFilename: "bundle-stats.json"
    })
  ],
  
  // Performance budgets
  performance: {
    maxAssetSize: 250000,
    maxEntrypointSize: 250000,
    hints: "warning",
    
    // Filter specific asset types
    assetFilter: (assetFilename) => {
      return assetFilename.endsWith('.js') || assetFilename.endsWith('.css');
    }
  }
};

Optimization Monitoring

module.exports = {
  stats: {
    // Optimization information
    optimizationBailout: true,
    chunks: true,
    chunkModules: true,
    chunkOrigins: true,
    
    // Performance metrics
    timings: true,
    builtAt: true,
    
    // Tree shaking information
    usedExports: true,
    providedExports: true,
    
    // Detailed module information
    modules: true,
    moduleTrace: true,
    reasons: true
  }
};

This comprehensive optimization documentation covers webpack's full optimization system, from basic configuration to advanced production strategies, providing developers with the tools to create highly optimized bundles for any use case.

Install with Tessl CLI

npx tessl i tessl/npm-webpack

docs

configuration.md

core-compilation.md

development-tools.md

index.md

module-system.md

optimization.md

plugins.md

runtime-system.md

utilities.md

tile.json