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

utilities.mddocs/

Utility Functions

Webpack provides a comprehensive suite of utility functions that support its core functionality. These utilities handle everything from hash creation and object merging to serialization, caching, error handling, and code generation. They are essential building blocks that enable webpack's modular architecture and plugin system.

Capabilities

Hash Creation Utilities

Webpack's hash creation system provides consistent, platform-independent hashing for content-based caching and file naming.

/**
 * Create hash function for webpack
 * @param algorithm - Hash algorithm to use (e.g., 'md4', 'md5', 'sha1', 'sha256')
 * @returns Hash instance for incremental hashing
 */
function createHash(algorithm: string): Hash;

/**
 * Create batch hash for multiple inputs
 * @param algorithm - Hash algorithm to use
 * @returns BatchedHash instance for batched operations
 */
function createBatchedHash(algorithm: string): BatchedHash;

interface Hash {
  /**
   * Update hash with new data
   * @param data - Data to hash
   * @param encoding - Input encoding (default: 'utf8')
   * @returns Hash instance for chaining
   */
  update(data: string | Buffer, encoding?: string): Hash;
  
  /**
   * Generate final hash digest
   * @param encoding - Output encoding (default: 'hex')
   * @returns Hash digest string
   */
  digest(encoding?: string): string;
}

interface BatchedHash extends Hash {
  /**
   * Add hash to batch
   * @param hash - Hash to add to batch
   */
  add(hash: Hash): void;
  
  /**
   * Flush batched hashes
   * @returns Combined hash digest
   */
  flush(): string;
}

Usage Examples:

const { createHash } = require("webpack/lib/util/createHash");

// Create content hash for caching
const hash = createHash("md4");
hash.update(moduleSource);
const contentHash = hash.digest("hex").substr(0, 8);

// Batch multiple hashes
const batchedHash = createBatchedHash("md4");
modules.forEach(module => {
  const moduleHash = createHash("md4");
  moduleHash.update(module.source());
  batchedHash.add(moduleHash);
});
const combinedHash = batchedHash.flush();

Comparison Utilities

Comparison functions for sorting and organizing webpack data structures.

/**
 * Collection of comparison functions for webpack objects
 */
interface Comparators {
  /**
   * Compare modules by identifier
   * @param a - First module
   * @param b - Second module
   * @returns Comparison result (-1, 0, 1)
   */
  compareModulesByIdentifier(a: Module, b: Module): number;
  
  /**
   * Compare modules by pre-order index
   * @param moduleGraph - Module graph instance
   * @returns Comparison function
   */
  compareModulesByPreOrderIndexOrIdentifier(moduleGraph: ModuleGraph): (a: Module, b: Module) => number;
  
  /**
   * Compare chunks by identifier
   * @param a - First chunk
   * @param b - Second chunk
   * @returns Comparison result (-1, 0, 1)
   */
  compareChunksByIdentifier(a: Chunk, b: Chunk): number;
  
  /**
   * Compare chunk groups by identifier
   * @param a - First chunk group
   * @param b - Second chunk group
   * @returns Comparison result (-1, 0, 1)
   */
  compareChunkGroupsByIdentifier(a: ChunkGroup, b: ChunkGroup): number;
  
  /**
   * Compare strings naturally
   * @param a - First string
   * @param b - Second string
   * @returns Comparison result (-1, 0, 1)
   */
  compareStringsNumeric(a: string, b: string): number;
  
  /**
   * Compare modules by post-order index
   * @param moduleGraph - Module graph instance
   * @returns Comparison function
   */
  compareModulesByPostOrderIndexOrIdentifier(moduleGraph: ModuleGraph): (a: Module, b: Module) => number;
  
  /**
   * Compare locations in source files
   * @param a - First location
   * @param b - Second location
   * @returns Comparison result (-1, 0, 1)
   */
  compareLocations(a: SourceLocation, b: SourceLocation): number;
}

const comparators: Comparators;

Usage Examples:

const { comparators } = require("webpack/lib/util/comparators");

// Sort modules by identifier
const sortedModules = modules.sort(comparators.compareModulesByIdentifier);

// Sort chunks by identifier
const sortedChunks = chunks.sort(comparators.compareChunksByIdentifier);

// Natural string comparison
const files = ["file1.js", "file10.js", "file2.js"];
files.sort(comparators.compareStringsNumeric);
// Result: ["file1.js", "file2.js", "file10.js"]

Runtime Utilities

Runtime helper functions for webpack's module system and chunk loading.

/**
 * Runtime utility functions for webpack
 */
interface RuntimeUtils {
  /**
   * Generate runtime code for module access
   * @param moduleId - Module identifier
   * @param optional - Whether module is optional
   * @returns Runtime code string
   */
  moduleAccessor(moduleId: string | number, optional?: boolean): string;
  
  /**
   * Generate runtime code for chunk loading
   * @param chunkId - Chunk identifier
   * @param runtimeRequirements - Required runtime features
   * @returns Runtime code string
   */
  chunkLoader(chunkId: string | number, runtimeRequirements: Set<string>): string;
  
  /**
   * Generate module namespace object
   * @param module - Module instance
   * @param exports - Module exports
   * @returns Namespace object code
   */
  createNamespaceObject(module: Module, exports: any): string;
  
  /**
   * Generate compatibility helper for ES modules
   * @param exports - Exports object
   * @returns Compatibility code
   */
  makeCompatibilityHelper(exports: any): string;
  
  /**
   * Get runtime chunk name
   * @param entrypoint - Entry point instance
   * @returns Runtime chunk name
   */
  getRuntimeChunkName(entrypoint: Entrypoint): string;
}

const runtime: RuntimeUtils;

Usage Examples:

const { runtime } = require("webpack/lib/util/runtime");

// Generate module accessor code
const moduleCode = runtime.moduleAccessor("./my-module", false);

// Generate chunk loader code
const chunkCode = runtime.chunkLoader("async-chunk", new Set(["__webpack_require__"]));

// Create namespace object
const namespaceCode = runtime.createNamespaceObject(module, moduleExports);

Serialization Utilities

Utilities for serializing and deserializing webpack data structures for caching and persistence.

/**
 * Serialization system for webpack data persistence
 */
interface SerializationUtils {
  /**
   * Register serializable type
   * @param Constructor - Constructor function
   * @param name - Serialization name
   * @param serializer - Custom serializer function
   */
  register(
    Constructor: Function,
    name: string,
    serializer?: {
      serialize: (obj: any, context: SerializationContext) => any;
      deserialize: (data: any, context: SerializationContext) => any;
    }
  ): void;
  
  /**
   * Create object serializer
   * @param obj - Object to serialize
   * @param context - Serialization context
   * @returns Serialized data
   */
  createObjectSerializer(obj: any, context: SerializationContext): any;
  
  /**
   * Create object deserializer
   * @param data - Serialized data
   * @param context - Serialization context
   * @returns Deserialized object
   */
  createObjectDeserializer(data: any, context: SerializationContext): any;
  
  /**
   * Serialize value to buffer
   * @param value - Value to serialize
   * @returns Buffer containing serialized data
   */
  serialize(value: any): Buffer;
  
  /**
   * Deserialize value from buffer
   * @param buffer - Buffer containing serialized data
   * @returns Deserialized value
   */
  deserialize(buffer: Buffer): any;
}

interface SerializationContext {
  /** Write method for serialization */
  write: (value: any) => void;
  /** Read method for deserialization */
  read: () => any;
  /** Serialization options */
  options?: SerializationOptions;
}

interface SerializationOptions {
  /** Freeze serialized objects */
  freeze?: boolean;
  /** Include source maps */
  sourceMaps?: boolean;
  /** Compression level */
  compression?: number;
}

const serialization: SerializationUtils;

Usage Examples:

const { serialization } = require("webpack/lib/util/serialization");

// Register custom class for serialization
class CustomData {
  constructor(value) {
    this.value = value;
  }
}

serialization.register(CustomData, "CustomData", {
  serialize: (obj, { write }) => {
    write(obj.value);
  },
  deserialize: ({ read }) => {
    return new CustomData(read());
  }
});

// Serialize and deserialize data
const data = { modules: [], chunks: [], customData: new CustomData("test") };
const buffer = serialization.serialize(data);
const restored = serialization.deserialize(buffer);

Smart Object Merging

Intelligent object merging with caching for configuration and options processing.

/**
 * Intelligent object merging with performance optimizations
 * @param first - First object to merge
 * @param second - Second object to merge
 * @returns Merged object with cached results
 */
function cleverMerge<T, U>(first: T, second: U): T & U;

/**
 * Cached merge function for repeated operations
 * @param first - First object to merge
 * @param second - Second object to merge
 * @returns Merged object from cache or new merge
 */
function cachedCleverMerge<T, U>(first: T, second: U): T & U;

/**
 * Clear merge cache
 */
function clearCache(): void;

/**
 * Configure merge behavior
 * @param options - Merge options
 */
function setMergeOptions(options: MergeOptions): void;

interface MergeOptions {
  /** Maximum cache size */
  maxCacheSize?: number;
  /** Deep merge arrays */
  mergeArrays?: boolean;
  /** Custom merge functions */
  customMergers?: Record<string, (a: any, b: any) => any>;
}

Usage Examples:

const { cleverMerge, cachedCleverMerge } = require("webpack/lib/util/cleverMerge");

// Merge webpack configurations
const baseConfig = {
  entry: "./src/index.js",
  output: { path: "/dist" },
  plugins: [new PluginA()]
};

const envConfig = {
  mode: "production",
  output: { filename: "[hash].js" },
  plugins: [new PluginB()]
};

const finalConfig = cleverMerge(baseConfig, envConfig);
// Result: merged configuration with intelligent handling

// Cached merge for repeated operations
const optimizedMerge = cachedCleverMerge(baseConfig, envConfig);

Lazy Set Data Structure

Memory-efficient lazy set implementation for managing large collections.

class LazySet<T> {
  /**
   * Constructor for LazySet
   * @param iterable - Initial items (optional)
   */
  constructor(iterable?: Iterable<T>);
  
  /**
   * Add item to set
   * @param item - Item to add
   * @returns LazySet instance for chaining
   */
  add(item: T): LazySet<T>;
  
  /**
   * Check if set contains item
   * @param item - Item to check
   * @returns True if item exists in set
   */
  has(item: T): boolean;
  
  /**
   * Remove item from set
   * @param item - Item to remove
   * @returns True if item was removed
   */
  delete(item: T): boolean;
  
  /**
   * Clear all items from set
   */
  clear(): void;
  
  /**
   * Get set size
   * @returns Number of items in set
   */
  get size(): number;
  
  /**
   * Iterate over set values
   * @returns Iterator for set values
   */
  values(): IterableIterator<T>;
  
  /**
   * Iterate over set entries
   * @returns Iterator for [value, value] pairs
   */
  entries(): IterableIterator<[T, T]>;
  
  /**
   * Execute callback for each item
   * @param callback - Function to execute for each item
   * @param thisArg - Value to use as 'this'
   */
  forEach(callback: (value: T, value2: T, set: LazySet<T>) => void, thisArg?: any): void;
  
  /**
   * Convert to regular Set
   * @returns Set instance with all items
   */
  toSet(): Set<T>;
  
  /**
   * Serialize set for caching
   * @returns Serialized representation
   */
  serialize(): any;
  
  /**
   * Deserialize set from cache
   * @param data - Serialized data
   * @returns LazySet instance
   */
  static deserialize<T>(data: any): LazySet<T>;
}

Usage Examples:

const { LazySet } = require("webpack/lib/util/LazySet");

// Create lazy set for modules
const moduleSet = new LazySet();

// Add modules as they're discovered
compilation.hooks.buildModule.tap("MyPlugin", (module) => {
  moduleSet.add(module);
});

// Efficient membership testing
if (moduleSet.has(targetModule)) {
  console.log("Module is in the set");
}

// Convert to regular set when needed
const regularSet = moduleSet.toSet();

Boolean Matching Compiler

Compiles boolean expressions for efficient module and resource matching.

/**
 * Compile boolean matcher expression
 * @param str - Boolean expression string
 * @returns Compiled matcher function
 */
function compileBooleanMatcher(str: string): BooleanMatcher;

/**
 * Compiled boolean matcher function
 * @param input - Input string to test
 * @returns True if input matches expression
 */
type BooleanMatcher = (input: string) => boolean;

/**
 * Parse boolean expression into AST
 * @param str - Expression string
 * @returns Parsed AST
 */
function parseBooleanExpression(str: string): BooleanExpressionNode;

/**
 * Optimize boolean expression for performance
 * @param expression - Boolean expression AST
 * @returns Optimized expression
 */
function optimizeBooleanExpression(expression: BooleanExpressionNode): BooleanExpressionNode;

interface BooleanExpressionNode {
  type: "literal" | "and" | "or" | "not" | "identifier";
  value?: string | boolean;
  left?: BooleanExpressionNode;
  right?: BooleanExpressionNode;
  expression?: BooleanExpressionNode;
}

Usage Examples:

const { compileBooleanMatcher } = require("webpack/lib/util/compileBooleanMatcher");

// Compile matcher for conditional builds
const matcher = compileBooleanMatcher("production && !development");

// Test against build conditions
const isMatch = matcher("production"); // true
const isMatchDev = matcher("development"); // false

// Complex expressions
const complexMatcher = compileBooleanMatcher("(web || electron) && !node");
console.log(complexMatcher("web")); // true
console.log(complexMatcher("node")); // false

Template System

Code generation template utilities for webpack's output system.

class Template {
  /**
   * Indent multiline strings
   * @param str - String to indent
   * @param prefix - Indentation prefix (default: "\t")
   * @returns Indented string
   */
  static indent(str: string | string[], prefix?: string): string;
  
  /**
   * Convert string to identifier
   * @param str - String to convert
   * @returns Valid JavaScript identifier
   */
  static toIdentifier(str: string): string;
  
  /**
   * Convert string to comment
   * @param str - String to convert
   * @returns Valid JavaScript comment
   */
  static toComment(str: string): string;
  
  /**
   * Convert to normal comment
   * @param str - String to convert
   * @returns Normal comment string
   */
  static toNormalComment(str: string): string;
  
  /**
   * Convert string to path
   * @param str - String to convert
   * @returns Path string
   */
  static toPath(str: string): string;
  
  /**
   * Generate number to identifier mapping
   * @param n - Number to convert
   * @returns Short identifier string
   */
  static numberToIdentifier(n: number): string;
  
  /**
   * Generate identifier to number mapping
   * @param identifier - Identifier string
   * @returns Corresponding number
   */
  static identifierToNumber(identifier: string): number;
  
  /**
   * Escape string for JavaScript
   * @param str - String to escape
   * @returns Escaped string
   */
  static quoteMeta(str: string): string;
  
  /**
   * Join array with separators
   * @param array - Array to join
   * @param separator - Separator string
   * @returns Joined string
   */
  static asString(array: (string | number)[], separator?: string): string;
  
  /**
   * Prefix each line with given string
   * @param str - String to process
   * @param prefix - Prefix for each line
   * @returns Prefixed string
   */
  static prefix(str: string, prefix: string): string;
  
  /**
   * Create property access string
   * @param properties - Property path array
   * @returns Property access code
   */
  static property(properties: (string | number)[]): string;
}

Usage Examples:

const { Template } = require("webpack/lib/Template");

// Generate indented code
const code = Template.indent([
  "function myFunction() {",
  Template.indent("return 'hello';"),
  "}"
]);

// Convert to valid identifier
const identifier = Template.toIdentifier("my-module-name"); // "my_module_name"

// Generate property access
const propertyAccess = Template.property(["exports", "default"]); // "exports.default"

// Create comments
const comment = Template.toComment("This is a generated module");

// Escape strings
const escaped = Template.quoteMeta("string with 'quotes'");

Statistics Classes

Compilation statistics and information management.

class Stats {
  /** Associated compilation */
  compilation: Compilation;
  
  /**
   * Constructor for Stats
   * @param compilation - Compilation instance
   */
  constructor(compilation: Compilation);
  
  /**
   * Check if compilation has errors
   * @returns True if errors exist
   */
  hasErrors(): boolean;
  
  /**
   * Check if compilation has warnings
   * @returns True if warnings exist
   */
  hasWarnings(): boolean;
  
  /**
   * Convert stats to JSON
   * @param options - Stats options
   * @returns JSON representation
   */
  toJson(options?: StatsOptions | string): StatsCompilation;
  
  /**
   * Convert stats to string
   * @param options - Stats options
   * @returns Formatted string
   */
  toString(options?: StatsOptions | string): string;
}

class MultiStats {
  /** Array of child stats */
  stats: Stats[];
  
  /**
   * Constructor for MultiStats
   * @param stats - Array of Stats instances
   */
  constructor(stats: Stats[]);
  
  /**
   * Check if any compilation has errors
   * @returns True if any errors exist
   */
  hasErrors(): boolean;
  
  /**
   * Check if any compilation has warnings
   * @returns True if any warnings exist
   */
  hasWarnings(): boolean;
  
  /**
   * Convert multi-stats to JSON
   * @param options - Stats options
   * @returns JSON representation with children array
   */
  toJson(options?: StatsOptions | string): { children: StatsCompilation[] };
  
  /**
   * Convert multi-stats to string
   * @param options - Stats options
   * @returns Formatted string representation
   */
  toString(options?: StatsOptions | string): string;
}

interface StatsOptions {
  /** Include asset information */
  assets?: boolean;
  /** Include chunk information */
  chunks?: boolean;
  /** Include module information */
  modules?: boolean;
  /** Include reasons for including modules */
  reasons?: boolean;
  /** Include source code of modules */
  source?: boolean;
  /** Include error details */
  errorDetails?: boolean;
  /** Maximum number of modules to show */
  maxModules?: number;
  /** Include colors in output */
  colors?: boolean;
  /** Include performance hints */
  performance?: boolean;
  /** Include timing information */
  timings?: boolean;
  /** Include built at timestamp */
  builtAt?: boolean;
  /** Include version information */
  version?: boolean;
  /** Include hash information */
  hash?: boolean;
  /** Include public path */
  publicPath?: boolean;
  /** Preset configurations */
  preset?: "errors-only" | "errors-warnings" | "minimal" | "normal" | "verbose";
}

Usage Examples:

const webpack = require("webpack");
const config = require("./webpack.config");

webpack(config, (err, stats) => {
  if (err || stats.hasErrors()) {
    console.error("Build failed!");
    if (stats) {
      console.error(stats.toString("errors-only"));
    }
    return;
  }
  
  // Success - show build info
  console.log(stats.toString({
    colors: true,
    chunks: false,
    modules: false,
    assets: true
  }));
  
  // Get detailed JSON stats
  const jsonStats = stats.toJson("verbose");
  console.log(`Build completed in ${jsonStats.time}ms`);
});

Caching System

Webpack's caching infrastructure for build performance optimization.

class Cache {
  /**
   * Constructor for Cache
   * @param options - Cache options
   */
  constructor(options: CacheOptions);
  
  /**
   * Get cache item
   * @param identifier - Cache key
   * @param etag - Entity tag for cache validation
   * @param callback - Callback with cached value
   */
  get<T>(
    identifier: string,
    etag: string | null,
    callback: (err: Error | null, result: T | null) => void
  ): void;
  
  /**
   * Store cache item
   * @param identifier - Cache key
   * @param etag - Entity tag for cache validation
   * @param data - Data to cache
   * @param callback - Completion callback
   */
  store<T>(
    identifier: string,
    etag: string | null,
    data: T,
    callback: (err?: Error) => void
  ): void;
  
  /**
   * Store build dependencies
   * @param dependencies - Build dependencies
   * @param callback - Completion callback
   */
  storeBuildDependencies(
    dependencies: Iterable<string>,
    callback: (err?: Error) => void
  ): void;
  
  /**
   * Begin idle period
   * @param callback - Completion callback
   */
  beginIdle(callback?: () => void): void;
  
  /**
   * End idle period
   * @param callback - Completion callback
   */
  endIdle(callback?: (err?: Error) => void): void;
  
  /**
   * Shutdown cache
   * @param callback - Completion callback
   */
  shutdown(callback?: (err?: Error) => void): void;
}

class CacheFacade {
  /**
   * Constructor for CacheFacade
   * @param cache - Underlying cache instance
   * @param name - Cache name/namespace
   * @param defaultTtl - Default TTL in milliseconds
   */
  constructor(cache: Cache, name: string, defaultTtl?: number);
  
  /**
   * Get item with promise interface
   * @param identifier - Cache key
   * @param etag - Entity tag for validation
   * @returns Promise with cached value
   */
  getPromise<T>(identifier: string, etag?: string | null): Promise<T | null>;
  
  /**
   * Store item with promise interface
   * @param identifier - Cache key
   * @param etag - Entity tag for validation
   * @param data - Data to cache
   * @returns Promise for completion
   */
  storePromise<T>(identifier: string, etag: string | null, data: T): Promise<void>;
  
  /**
   * Provide cached or computed value
   * @param identifier - Cache key
   * @param etag - Entity tag for validation
   * @param computer - Function to compute value if not cached
   * @returns Promise with value
   */
  provide<T>(
    identifier: string,
    etag: string | null,
    computer: () => T | Promise<T>
  ): Promise<T>;
}

interface CacheOptions {
  /** Cache type */
  type?: "memory" | "filesystem";
  /** Cache directory for filesystem cache */
  cacheDirectory?: string;
  /** Build dependencies */
  buildDependencies?: Record<string, string[]>;
  /** Cache name */
  name?: string;
  /** Cache version */
  version?: string;
  /** Maximum age in milliseconds */
  maxAge?: number;
  /** Maximum memory usage */
  maxMemoryUsage?: number;
  /** Compression */
  compression?: false | "gzip" | "brotli";
}

Usage Examples:

const { Cache, CacheFacade } = require("webpack/lib/Cache");

// Create cache with filesystem backend
const cache = new Cache({
  type: "filesystem",
  cacheDirectory: "./node_modules/.cache/webpack",
  buildDependencies: {
    config: ["webpack.config.js"],
    code: ["src/**"]
  }
});

// Create facade for specific cache namespace
const moduleCache = new CacheFacade(cache, "modules", 1000 * 60 * 60); // 1 hour TTL

// Cache expensive computation
const result = await moduleCache.provide(
  "my-module-key",
  "etag-12345",
  async () => {
    // Expensive computation here
    return await processModule(moduleSource);
  }
);

// Direct cache operations
moduleCache.storePromise("processed-module", "v1", processedData);
const cached = await moduleCache.getPromise("processed-module", "v1");

Error Handling

Webpack-specific error classes for consistent error handling throughout the build process.

class WebpackError extends Error {
  /** Error name */
  name: string;
  
  /** Error message */
  message: string;
  
  /** Error details */
  details?: string;
  
  /** Module that caused the error */
  module?: Module;
  
  /** Location in source where error occurred */
  loc?: SourceLocation;
  
  /** Hide error stack trace */
  hideStack?: boolean;
  
  /** Error chunk */
  chunk?: Chunk;
  
  /** Error file */
  file?: string;
  
  /**
   * Constructor for WebpackError
   * @param message - Error message
   * @param module - Associated module
   */
  constructor(message?: string, module?: Module);
  
  /**
   * Serialize error for caching
   * @param context - Serialization context
   * @returns Serialized error data
   */
  serialize(context: SerializationContext): any;
  
  /**
   * Deserialize error from cache
   * @param context - Serialization context
   * @returns WebpackError instance
   */
  static deserialize(context: SerializationContext): WebpackError;
}

class ModuleError extends WebpackError {
  /** Module that caused the error */
  module: Module;
  
  /**
   * Constructor for ModuleError
   * @param message - Error message
   * @param module - Module that caused error
   */
  constructor(message: string, module: Module);
}

class ModuleWarning extends WebpackError {
  /** Module that caused the warning */
  module: Module;
  
  /**
   * Constructor for ModuleWarning
   * @param message - Warning message
   * @param module - Module that caused warning
   */
  constructor(message: string, module: Module);
}

class ValidationError extends Error {
  /** Validation errors array */
  errors: ValidationErrorInfo[];
  
  /**
   * Constructor for ValidationError
   * @param errors - Array of validation errors
   * @param schema - Schema that was validated against
   * @param configuration - Configuration that failed validation
   */
  constructor(
    errors: ValidationErrorInfo[],
    schema: any,
    configuration: any
  );
}

interface ValidationErrorInfo {
  /** Property path that failed validation */
  dataPath: string;
  /** Schema path */
  schemaPath: string;
  /** Error keyword */
  keyword: string;
  /** Parameters for the error */
  params: Record<string, any>;
  /** Error message */
  message?: string;
}

interface SourceLocation {
  /** Line number (1-based) */
  line: number;
  /** Column number (0-based) */
  column: number;
  /** Character index */
  index?: number;
}

Usage Examples:

const { WebpackError, ModuleError, ValidationError } = require("webpack/lib/WebpackError");

// Create custom webpack error
class CustomBuildError extends WebpackError {
  constructor(message, module) {
    super(message, module);
    this.name = "CustomBuildError";
  }
}

// Throw module-specific error
if (moduleHasIssue) {
  throw new ModuleError("Module processing failed", module);
}

// Handle validation errors
try {
  validateConfiguration(config);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Configuration validation failed:");
    error.errors.forEach(err => {
      console.error(`  ${err.dataPath}: ${err.message}`);
    });
  }
}

Module Filename Utilities

Utilities for working with module filenames and paths in webpack's build process.

/**
 * Module filename helper utilities
 */
interface ModuleFilenameHelpers {
  /**
   * Create filename template function
   * @param template - Filename template string
   * @param options - Template options
   * @returns Function that generates filenames
   */
  createFilename(
    template: string | Function,
    options?: FilenameTemplateOptions
  ): (pathData: PathData) => string;
  
  /**
   * Replace path variables in template
   * @param template - Template string with variables
   * @param pathData - Data for variable replacement
   * @param assetInfo - Asset information
   * @returns Resolved template string
   */
  replaceDuplicates(
    template: string,
    pathData: PathData,
    assetInfo?: AssetInfo
  ): string;
  
  /**
   * Create filter function from test patterns
   * @param tests - Test patterns (string, RegExp, or array)
   * @returns Filter function
   */
  matchPart(tests: TestPatterns): (filename: string) => boolean;
  
  /**
   * Create object filter function
   * @param tests - Test patterns for object properties
   * @returns Object filter function
   */
  matchObject(tests: Record<string, TestPatterns>): (obj: Record<string, any>) => boolean;
  
  /**
   * Get absolute filename from module
   * @param module - Module instance
   * @returns Absolute filename or empty string
   */
  absolutify(module: Module): string;
  
  /**
   * Shorten absolute paths for display
   * @param filename - Absolute filename
   * @param context - Base context path
   * @returns Shortened relative path
   */
  contextify(filename: string, context: string): string;
}

type TestPatterns = string | RegExp | Array<string | RegExp> | ((value: string) => boolean);

interface PathData {
  /** Chunk information */
  chunk?: Chunk;
  /** Module information */
  module?: Module;
  /** Hash information */
  hash?: string;
  /** Content hash information */
  contenthash?: string;
  /** Chunk hash information */
  chunkhash?: string;
  /** Filename without query/fragment */
  filename?: string;
  /** Base name without extension */
  basename?: string;
  /** Query string */
  query?: string;
  /** Fragment identifier */
  fragment?: string;
  /** File extension */
  ext?: string;
  /** File path without filename */
  path?: string;
}

interface FilenameTemplateOptions {
  /** No hash length limit */
  noHashLength?: boolean;
  /** Context for relative paths */
  context?: string;
  /** Content hash type */
  contenthashType?: string;
  /** Hash digest encoding */
  hashDigest?: string;
  /** Hash digest length */
  hashDigestLength?: number;
  /** Hash function */
  hashFunction?: string;
  /** Hash salt */
  hashSalt?: string;
}

const ModuleFilenameHelpers: ModuleFilenameHelpers;

Usage Examples:

const { ModuleFilenameHelpers } = require("webpack/lib/ModuleFilenameHelpers");

// Create filename template function
const filenameTemplate = ModuleFilenameHelpers.createFilename(
  "[name].[contenthash:8].js",
  { hashDigestLength: 8 }
);

// Generate filename from path data
const filename = filenameTemplate({
  chunk: myChunk,
  hash: "abcdef123456",
  contenthash: "xyz789",
  basename: "main"
});

// Create filter for matching modules
const testFilter = ModuleFilenameHelpers.matchPart([
  /\.js$/,
  /\.jsx$/,
  "specific-module.js"
]);

// Filter modules
const jsModules = modules.filter(module => {
  return testFilter(module.resource || "");
});

// Shorten paths for display
const shortPath = ModuleFilenameHelpers.contextify(
  "/full/path/to/project/src/module.js",
  "/full/path/to/project"
); // "src/module.js"

Request Shortener

Utility for shortening module request paths for cleaner output and debugging.

class RequestShortener {
  /**
   * Constructor for RequestShortener
   * @param context - Base context directory
   * @param associatedObjectForCache - Object for cache association
   */
  constructor(context: string, associatedObjectForCache?: any);
  
  /**
   * Shorten absolute path relative to context
   * @param request - Absolute path to shorten
   * @returns Shortened path
   */
  shorten(request: string): string;
  
  /**
   * Shorten request with custom context
   * @param request - Request to shorten
   * @param context - Custom context path
   * @returns Shortened request
   */
  relatify(request: string, context?: string): string;
}

Usage Examples:

const { RequestShortener } = require("webpack/lib/RequestShortener");

// Create request shortener for project
const shortener = new RequestShortener("/project/root");

// Shorten module requests
const shortened = shortener.shorten("/project/root/src/components/Button.js");
// Result: "./src/components/Button.js"

const external = shortener.shorten("/node_modules/react/index.js");
// Result: "react/index.js"

// Custom context shortening
const relative = shortener.relatify(
  "/project/root/src/utils/helper.js",
  "/project/root/src/components"
);
// Result: "../utils/helper.js"

External Dependencies Integration

Integration utilities for external dependencies, particularly webpack-sources for source manipulation.

/**
 * webpack-sources integration utilities
 */
interface Sources {
  /** Raw source without transformation */
  RawSource: typeof RawSource;
  /** Original source with source map support */
  OriginalSource: typeof OriginalSource;
  /** Source with replacement capabilities */
  ReplaceSource: typeof ReplaceSource;
  /** Concatenated source from multiple sources */
  ConcatSource: typeof ConcatSource;
  /** Prefix source with additional content */
  PrefixSource: typeof PrefixSource;
  /** Cached source with lazy evaluation */
  CachedSource: typeof CachedSource;
  /** Size-only source for measurements */
  SizeOnlySource: typeof SizeOnlySource;
  /** Compatibility source wrapper */
  CompatSource: typeof CompatSource;
}

class RawSource {
  /**
   * Constructor for raw source
   * @param value - Source code string or buffer
   * @param convertToString - Whether to convert buffer to string
   */
  constructor(value: string | Buffer, convertToString?: boolean);
  
  /** Get source content */
  source(): string | Buffer;
  
  /** Get source map */
  sourceAndMap(options?: SourceMapOptions): { source: string | Buffer; map: SourceMap };
  
  /** Get source size */
  size(): number;
  
  /** Update hash with source content */
  updateHash(hash: Hash): void;
}

class OriginalSource {
  /**
   * Constructor for original source with source map
   * @param value - Source code
   * @param name - Source name/filename
   */
  constructor(value: string, name: string);
  
  /** Get source content */
  source(): string;
  
  /** Get original source map */
  sourceAndMap(options?: SourceMapOptions): { source: string; map: SourceMap };
  
  /** Get source size */
  size(): number;
}

class ConcatSource {
  /**
   * Constructor for concatenated source
   * @param sources - Sources to concatenate
   */
  constructor(...sources: (Source | string)[]);
  
  /**
   * Add source to concatenation
   * @param item - Source or string to add
   */
  add(item: Source | string): void;
  
  /** Get concatenated source */
  source(): string;
  
  /** Get source size */
  size(): number;
}

interface SourceMapOptions {
  /** Include source content in map */
  includeSourcesContent?: boolean;
  /** Module identifier */
  module?: boolean;
  /** Column mappings */
  columns?: boolean;
}

const sources: Sources;

Usage Examples:

const { sources } = require("webpack");
const { RawSource, ConcatSource, OriginalSource } = sources;

// Create raw source
const moduleSource = new RawSource('console.log("Hello World");');

// Concatenate multiple sources
const bundleSource = new ConcatSource(
  '(function() {\n',
  new RawSource('var exports = {};\n'),
  moduleSource,
  '\nreturn exports;\n',
  '})()'
);

// Original source with source map
const originalSource = new OriginalSource(
  'const message = "Hello";\nconsole.log(message);',
  'original-file.js'
);

// Get combined source
const finalSource = bundleSource.source();
const sourceMap = originalSource.sourceAndMap();

CLI Interface Utilities

Command-line interface utilities for webpack's CLI functionality.

/**
 * CLI interface utilities
 */
interface CLIUtils {
  /**
   * Parse CLI arguments
   * @param args - Command line arguments array
   * @returns Parsed options object
   */
  parseArgs(args: string[]): CLIOptions;
  
  /**
   * Process webpack configuration from CLI
   * @param options - CLI options
   * @returns Webpack configuration
   */
  processConfigOptions(options: CLIOptions): Configuration;
  
  /**
   * Setup compiler with CLI options
   * @param config - Webpack configuration
   * @param options - CLI options
   * @returns Configured compiler
   */
  setupCompiler(config: Configuration, options: CLIOptions): Compiler;
  
  /**
   * Run webpack with CLI options
   * @param compiler - Webpack compiler
   * @param options - CLI options
   * @param callback - Completion callback
   */
  runCompiler(
    compiler: Compiler,
    options: CLIOptions,
    callback: (err: Error | null, stats?: Stats) => void
  ): void;
  
  /**
   * Format stats output for CLI
   * @param stats - Compilation stats
   * @param options - Format options
   * @returns Formatted output string
   */
  formatStats(stats: Stats, options?: StatsFormatOptions): string;
  
  /**
   * Handle CLI errors and exit codes
   * @param error - Error to handle
   * @param stats - Optional stats for context
   * @returns Exit code
   */
  handleError(error: Error | null, stats?: Stats): number;
}

interface CLIOptions {
  /** Entry point files */
  entry?: string | string[];
  /** Output configuration */
  output?: string;
  /** Build mode */
  mode?: "development" | "production" | "none";
  /** Configuration file path */
  config?: string;
  /** Environment variables */
  env?: Record<string, any>;
  /** Watch mode */
  watch?: boolean;
  /** Development server */
  devServer?: boolean;
  /** Stats output format */
  stats?: string | StatsOptions;
  /** Colors in output */
  color?: boolean;
  /** Progress reporting */
  progress?: boolean;
  /** Bail on first error */
  bail?: boolean;
  /** Profile performance */
  profile?: boolean;
  /** JSON output */
  json?: boolean | string;
}

interface StatsFormatOptions {
  /** Include colors */
  colors?: boolean;
  /** Show cached modules */
  cached?: boolean;
  /** Show cached assets */
  cachedAssets?: boolean;
  /** Exclude modules */
  exclude?: string | RegExp | Array<string | RegExp>;
  /** Maximum modules to display */
  maxModules?: number;
  /** Show reasons */
  reasons?: boolean;
  /** Show depth */
  depth?: boolean;
  /** Show used exports */
  usedExports?: boolean;
  /** Show provided exports */
  providedExports?: boolean;
}

const cli: CLIUtils;

Usage Examples:

const { cli } = require("webpack/lib/cli");

// Parse command line arguments
const options = cli.parseArgs(process.argv.slice(2));

// Process configuration from CLI options
const config = cli.processConfigOptions(options);

// Setup and run compiler
const compiler = cli.setupCompiler(config, options);

cli.runCompiler(compiler, options, (err, stats) => {
  if (err) {
    const exitCode = cli.handleError(err, stats);
    process.exit(exitCode);
  }
  
  // Format and display stats
  const output = cli.formatStats(stats, {
    colors: options.color,
    cached: false,
    reasons: options.verbose
  });
  
  console.log(output);
});

// Handle different output formats
if (options.json) {
  const jsonOutput = stats.toJson();
  if (typeof options.json === 'string') {
    require('fs').writeFileSync(options.json, JSON.stringify(jsonOutput, null, 2));
  } else {
    console.log(JSON.stringify(jsonOutput));
  }
}

Runtime Utilities

Runtime-related utilities for module execution, chunk loading, and runtime code generation in different environments.

/**
 * Runtime utilities for webpack's generated code
 */
const runtime: {
  /**
   * Get the current runtime
   * @returns Runtime identifier
   */
  getRuntime(): string | undefined;
  
  /**
   * Merge runtime sets
   * @param a - First runtime set
   * @param b - Second runtime set
   * @returns Merged runtime set
   */
  mergeRuntime(a: RuntimeSpec | undefined, b: RuntimeSpec | undefined): RuntimeSpec | undefined;
  
  /**
   * Subtract runtime from another
   * @param a - Base runtime set
   * @param b - Runtime set to subtract
   * @returns Resulting runtime set
   */
  subtractRuntime(a: RuntimeSpec | undefined, b: RuntimeSpec | undefined): RuntimeSpec | undefined;
  
  /**
   * Convert runtime to string
   * @param runtime - Runtime spec to stringify
   * @returns String representation
   */
  runtimeToString(runtime: RuntimeSpec): string;
  
  /**
   * Get all chunk runtime requirements
   * @param chunks - Chunks to analyze
   * @returns Set of runtime requirements
   */
  getChunkRuntimeRequirements(chunks: Iterable<Chunk>): Set<string>;
};

type RuntimeSpec = string | SortableSet<string> | boolean | undefined;

Serialization Utilities

Serialization and deserialization utilities for webpack's caching and persistence systems.

/**
 * Serialization utilities for webpack's caching system
 */
const serialization: {
  /**
   * Register a serializable class
   * @param constructor - Class constructor to register
   * @param name - Serialization name
   * @param serializer - Custom serializer object
   */
  register(constructor: any, name: string, serializer?: ObjectSerializer): void;
  
  /**
   * Create a binary serializer for efficient storage
   * @returns Binary serializer instance
   */
  createBinarySerializer(): BinarySerializer;
  
  /**
   * Create a hash serializer for content hashing
   * @returns Hash serializer instance
   */
  createHashSerializer(): HashSerializer;
  
  /**
   * Create a file serializer for disk caching
   * @param fs - File system to use
   * @returns File serializer instance
   */
  createFileSerializer(fs: FileSystem): FileSerializer;
};

interface ObjectSerializer {
  serialize(obj: any, context: ObjectSerializerContext): void;
  deserialize(context: ObjectDeserializerContext): any;
}

interface BinarySerializer {
  serialize(obj: any): Buffer;
  deserialize(buffer: Buffer): any;
}

Boolean Matcher Utilities

Utilities for creating efficient boolean matching functions from configuration patterns.

/**
 * Compile a boolean matcher function from patterns
 * @param str - Pattern string or function
 * @returns Optimized boolean matcher function
 */
function compileBooleanMatcher(str: string | ((str: string) => boolean)): (str: string) => boolean;

/**
 * Create cached boolean matcher for better performance
 * @param str - Pattern string or function
 * @returns Cached boolean matcher function
 */
function createCachedBooleanMatcher(str: string | ((str: string) => boolean)): (str: string) => boolean;

Webpack Sources Integration

Integration with the webpack-sources library for source code manipulation and source map generation.

/**
 * Webpack sources library exports for source manipulation
 */
const sources: {
  Source: typeof Source;
  RawSource: typeof RawSource;
  OriginalSource: typeof OriginalSource;
  ReplaceSource: typeof ReplaceSource;
  SourceMapSource: typeof SourceMapSource;
  ConcatSource: typeof ConcatSource;
  PrefixSource: typeof PrefixSource;
  CachedSource: typeof CachedSource;
  SizeOnlySource: typeof SizeOnlySource;
  CompatSource: typeof CompatSource;
};

// Basic source types from webpack-sources
interface Source {
  source(): string | Buffer;
  buffer(): Buffer;
  size(): number;
  map(options?: any): Object | null;
  sourceAndMap(options?: any): { source: string | Buffer; map: Object | null };
  updateHash(hash: Hash): void;
}

class RawSource implements Source {
  constructor(source: string | Buffer, convertToString?: boolean);
  source(): string | Buffer;
  buffer(): Buffer;
  size(): number;
  map(options?: any): null;
  sourceAndMap(options?: any): { source: string | Buffer; map: null };
  updateHash(hash: Hash): void;
}

class ConcatSource implements Source {
  constructor(...sources: (string | Source)[]);
  add(source: string | Source): void;
  source(): string;
  buffer(): Buffer;
  size(): number;
  map(options?: any): Object | null;
  sourceAndMap(options?: any): { source: string; map: Object | null };
  updateHash(hash: Hash): void;
}

Common Types

interface Module {
  /** Module identifier */
  identifier(): string;
  /** Module resource path */
  resource?: string;
  /** Module type */
  type: string;
  /** Module source */
  source(): Source;
  /** Module size */
  size(): number;
  /** Module hash */
  hash?: string;
  /** Build info */
  buildInfo?: BuildInfo;
  /** Build meta */
  buildMeta?: BuildMeta;
}

interface Chunk {
  /** Chunk identifier */
  id: string | number | null;
  /** Chunk name */
  name?: string;
  /** Chunk hash */
  hash?: string;
  /** Content hash */
  contentHash: Record<string, string>;
  /** Chunk files */
  files: Set<string>;
  /** Chunk size */
  size(): number;
}

interface ChunkGroup {
  /** Chunk group name */
  name?: string;
  /** Child chunks */
  chunks: Chunk[];
  /** Parent groups */
  parents: Set<ChunkGroup>;
  /** Children groups */
  children: Set<ChunkGroup>;
}

interface Source {
  source(): string | Buffer;
  size(): number;
  sourceAndMap(options?: any): { source: string | Buffer; map: any };
  updateHash(hash: Hash): void;
}

This comprehensive documentation covers all of webpack's utility functions, providing detailed API signatures, interfaces, and practical usage examples. The utilities form the foundation that enables webpack's modular architecture, efficient caching, smart optimizations, and extensible plugin system. Each utility is designed to solve specific challenges in modern JavaScript bundling and can be leveraged by both webpack's internal systems and external plugins.

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