or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

configuration.mdcore-compilation.mddevelopment-tools.mdindex.mdmodule-system.mdoptimization.mdplugins.mdruntime-system.mdutilities.md

utilities.mddocs/

0

# Utility Functions

1

2

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.

3

4

## Capabilities

5

6

### Hash Creation Utilities

7

8

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

9

10

```javascript { .api }

11

/**

12

* Create hash function for webpack

13

* @param algorithm - Hash algorithm to use (e.g., 'md4', 'md5', 'sha1', 'sha256')

14

* @returns Hash instance for incremental hashing

15

*/

16

function createHash(algorithm: string): Hash;

17

18

/**

19

* Create batch hash for multiple inputs

20

* @param algorithm - Hash algorithm to use

21

* @returns BatchedHash instance for batched operations

22

*/

23

function createBatchedHash(algorithm: string): BatchedHash;

24

25

interface Hash {

26

/**

27

* Update hash with new data

28

* @param data - Data to hash

29

* @param encoding - Input encoding (default: 'utf8')

30

* @returns Hash instance for chaining

31

*/

32

update(data: string | Buffer, encoding?: string): Hash;

33

34

/**

35

* Generate final hash digest

36

* @param encoding - Output encoding (default: 'hex')

37

* @returns Hash digest string

38

*/

39

digest(encoding?: string): string;

40

}

41

42

interface BatchedHash extends Hash {

43

/**

44

* Add hash to batch

45

* @param hash - Hash to add to batch

46

*/

47

add(hash: Hash): void;

48

49

/**

50

* Flush batched hashes

51

* @returns Combined hash digest

52

*/

53

flush(): string;

54

}

55

```

56

57

**Usage Examples:**

58

59

```javascript

60

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

61

62

// Create content hash for caching

63

const hash = createHash("md4");

64

hash.update(moduleSource);

65

const contentHash = hash.digest("hex").substr(0, 8);

66

67

// Batch multiple hashes

68

const batchedHash = createBatchedHash("md4");

69

modules.forEach(module => {

70

const moduleHash = createHash("md4");

71

moduleHash.update(module.source());

72

batchedHash.add(moduleHash);

73

});

74

const combinedHash = batchedHash.flush();

75

```

76

77

### Comparison Utilities

78

79

Comparison functions for sorting and organizing webpack data structures.

80

81

```javascript { .api }

82

/**

83

* Collection of comparison functions for webpack objects

84

*/

85

interface Comparators {

86

/**

87

* Compare modules by identifier

88

* @param a - First module

89

* @param b - Second module

90

* @returns Comparison result (-1, 0, 1)

91

*/

92

compareModulesByIdentifier(a: Module, b: Module): number;

93

94

/**

95

* Compare modules by pre-order index

96

* @param moduleGraph - Module graph instance

97

* @returns Comparison function

98

*/

99

compareModulesByPreOrderIndexOrIdentifier(moduleGraph: ModuleGraph): (a: Module, b: Module) => number;

100

101

/**

102

* Compare chunks by identifier

103

* @param a - First chunk

104

* @param b - Second chunk

105

* @returns Comparison result (-1, 0, 1)

106

*/

107

compareChunksByIdentifier(a: Chunk, b: Chunk): number;

108

109

/**

110

* Compare chunk groups by identifier

111

* @param a - First chunk group

112

* @param b - Second chunk group

113

* @returns Comparison result (-1, 0, 1)

114

*/

115

compareChunkGroupsByIdentifier(a: ChunkGroup, b: ChunkGroup): number;

116

117

/**

118

* Compare strings naturally

119

* @param a - First string

120

* @param b - Second string

121

* @returns Comparison result (-1, 0, 1)

122

*/

123

compareStringsNumeric(a: string, b: string): number;

124

125

/**

126

* Compare modules by post-order index

127

* @param moduleGraph - Module graph instance

128

* @returns Comparison function

129

*/

130

compareModulesByPostOrderIndexOrIdentifier(moduleGraph: ModuleGraph): (a: Module, b: Module) => number;

131

132

/**

133

* Compare locations in source files

134

* @param a - First location

135

* @param b - Second location

136

* @returns Comparison result (-1, 0, 1)

137

*/

138

compareLocations(a: SourceLocation, b: SourceLocation): number;

139

}

140

141

const comparators: Comparators;

142

```

143

144

**Usage Examples:**

145

146

```javascript

147

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

148

149

// Sort modules by identifier

150

const sortedModules = modules.sort(comparators.compareModulesByIdentifier);

151

152

// Sort chunks by identifier

153

const sortedChunks = chunks.sort(comparators.compareChunksByIdentifier);

154

155

// Natural string comparison

156

const files = ["file1.js", "file10.js", "file2.js"];

157

files.sort(comparators.compareStringsNumeric);

158

// Result: ["file1.js", "file2.js", "file10.js"]

159

```

160

161

### Runtime Utilities

162

163

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

164

165

```javascript { .api }

166

/**

167

* Runtime utility functions for webpack

168

*/

169

interface RuntimeUtils {

170

/**

171

* Generate runtime code for module access

172

* @param moduleId - Module identifier

173

* @param optional - Whether module is optional

174

* @returns Runtime code string

175

*/

176

moduleAccessor(moduleId: string | number, optional?: boolean): string;

177

178

/**

179

* Generate runtime code for chunk loading

180

* @param chunkId - Chunk identifier

181

* @param runtimeRequirements - Required runtime features

182

* @returns Runtime code string

183

*/

184

chunkLoader(chunkId: string | number, runtimeRequirements: Set<string>): string;

185

186

/**

187

* Generate module namespace object

188

* @param module - Module instance

189

* @param exports - Module exports

190

* @returns Namespace object code

191

*/

192

createNamespaceObject(module: Module, exports: any): string;

193

194

/**

195

* Generate compatibility helper for ES modules

196

* @param exports - Exports object

197

* @returns Compatibility code

198

*/

199

makeCompatibilityHelper(exports: any): string;

200

201

/**

202

* Get runtime chunk name

203

* @param entrypoint - Entry point instance

204

* @returns Runtime chunk name

205

*/

206

getRuntimeChunkName(entrypoint: Entrypoint): string;

207

}

208

209

const runtime: RuntimeUtils;

210

```

211

212

**Usage Examples:**

213

214

```javascript

215

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

216

217

// Generate module accessor code

218

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

219

220

// Generate chunk loader code

221

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

222

223

// Create namespace object

224

const namespaceCode = runtime.createNamespaceObject(module, moduleExports);

225

```

226

227

### Serialization Utilities

228

229

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

230

231

```javascript { .api }

232

/**

233

* Serialization system for webpack data persistence

234

*/

235

interface SerializationUtils {

236

/**

237

* Register serializable type

238

* @param Constructor - Constructor function

239

* @param name - Serialization name

240

* @param serializer - Custom serializer function

241

*/

242

register(

243

Constructor: Function,

244

name: string,

245

serializer?: {

246

serialize: (obj: any, context: SerializationContext) => any;

247

deserialize: (data: any, context: SerializationContext) => any;

248

}

249

): void;

250

251

/**

252

* Create object serializer

253

* @param obj - Object to serialize

254

* @param context - Serialization context

255

* @returns Serialized data

256

*/

257

createObjectSerializer(obj: any, context: SerializationContext): any;

258

259

/**

260

* Create object deserializer

261

* @param data - Serialized data

262

* @param context - Serialization context

263

* @returns Deserialized object

264

*/

265

createObjectDeserializer(data: any, context: SerializationContext): any;

266

267

/**

268

* Serialize value to buffer

269

* @param value - Value to serialize

270

* @returns Buffer containing serialized data

271

*/

272

serialize(value: any): Buffer;

273

274

/**

275

* Deserialize value from buffer

276

* @param buffer - Buffer containing serialized data

277

* @returns Deserialized value

278

*/

279

deserialize(buffer: Buffer): any;

280

}

281

282

interface SerializationContext {

283

/** Write method for serialization */

284

write: (value: any) => void;

285

/** Read method for deserialization */

286

read: () => any;

287

/** Serialization options */

288

options?: SerializationOptions;

289

}

290

291

interface SerializationOptions {

292

/** Freeze serialized objects */

293

freeze?: boolean;

294

/** Include source maps */

295

sourceMaps?: boolean;

296

/** Compression level */

297

compression?: number;

298

}

299

300

const serialization: SerializationUtils;

301

```

302

303

**Usage Examples:**

304

305

```javascript

306

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

307

308

// Register custom class for serialization

309

class CustomData {

310

constructor(value) {

311

this.value = value;

312

}

313

}

314

315

serialization.register(CustomData, "CustomData", {

316

serialize: (obj, { write }) => {

317

write(obj.value);

318

},

319

deserialize: ({ read }) => {

320

return new CustomData(read());

321

}

322

});

323

324

// Serialize and deserialize data

325

const data = { modules: [], chunks: [], customData: new CustomData("test") };

326

const buffer = serialization.serialize(data);

327

const restored = serialization.deserialize(buffer);

328

```

329

330

### Smart Object Merging

331

332

Intelligent object merging with caching for configuration and options processing.

333

334

```javascript { .api }

335

/**

336

* Intelligent object merging with performance optimizations

337

* @param first - First object to merge

338

* @param second - Second object to merge

339

* @returns Merged object with cached results

340

*/

341

function cleverMerge<T, U>(first: T, second: U): T & U;

342

343

/**

344

* Cached merge function for repeated operations

345

* @param first - First object to merge

346

* @param second - Second object to merge

347

* @returns Merged object from cache or new merge

348

*/

349

function cachedCleverMerge<T, U>(first: T, second: U): T & U;

350

351

/**

352

* Clear merge cache

353

*/

354

function clearCache(): void;

355

356

/**

357

* Configure merge behavior

358

* @param options - Merge options

359

*/

360

function setMergeOptions(options: MergeOptions): void;

361

362

interface MergeOptions {

363

/** Maximum cache size */

364

maxCacheSize?: number;

365

/** Deep merge arrays */

366

mergeArrays?: boolean;

367

/** Custom merge functions */

368

customMergers?: Record<string, (a: any, b: any) => any>;

369

}

370

```

371

372

**Usage Examples:**

373

374

```javascript

375

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

376

377

// Merge webpack configurations

378

const baseConfig = {

379

entry: "./src/index.js",

380

output: { path: "/dist" },

381

plugins: [new PluginA()]

382

};

383

384

const envConfig = {

385

mode: "production",

386

output: { filename: "[hash].js" },

387

plugins: [new PluginB()]

388

};

389

390

const finalConfig = cleverMerge(baseConfig, envConfig);

391

// Result: merged configuration with intelligent handling

392

393

// Cached merge for repeated operations

394

const optimizedMerge = cachedCleverMerge(baseConfig, envConfig);

395

```

396

397

### Lazy Set Data Structure

398

399

Memory-efficient lazy set implementation for managing large collections.

400

401

```javascript { .api }

402

class LazySet<T> {

403

/**

404

* Constructor for LazySet

405

* @param iterable - Initial items (optional)

406

*/

407

constructor(iterable?: Iterable<T>);

408

409

/**

410

* Add item to set

411

* @param item - Item to add

412

* @returns LazySet instance for chaining

413

*/

414

add(item: T): LazySet<T>;

415

416

/**

417

* Check if set contains item

418

* @param item - Item to check

419

* @returns True if item exists in set

420

*/

421

has(item: T): boolean;

422

423

/**

424

* Remove item from set

425

* @param item - Item to remove

426

* @returns True if item was removed

427

*/

428

delete(item: T): boolean;

429

430

/**

431

* Clear all items from set

432

*/

433

clear(): void;

434

435

/**

436

* Get set size

437

* @returns Number of items in set

438

*/

439

get size(): number;

440

441

/**

442

* Iterate over set values

443

* @returns Iterator for set values

444

*/

445

values(): IterableIterator<T>;

446

447

/**

448

* Iterate over set entries

449

* @returns Iterator for [value, value] pairs

450

*/

451

entries(): IterableIterator<[T, T]>;

452

453

/**

454

* Execute callback for each item

455

* @param callback - Function to execute for each item

456

* @param thisArg - Value to use as 'this'

457

*/

458

forEach(callback: (value: T, value2: T, set: LazySet<T>) => void, thisArg?: any): void;

459

460

/**

461

* Convert to regular Set

462

* @returns Set instance with all items

463

*/

464

toSet(): Set<T>;

465

466

/**

467

* Serialize set for caching

468

* @returns Serialized representation

469

*/

470

serialize(): any;

471

472

/**

473

* Deserialize set from cache

474

* @param data - Serialized data

475

* @returns LazySet instance

476

*/

477

static deserialize<T>(data: any): LazySet<T>;

478

}

479

```

480

481

**Usage Examples:**

482

483

```javascript

484

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

485

486

// Create lazy set for modules

487

const moduleSet = new LazySet();

488

489

// Add modules as they're discovered

490

compilation.hooks.buildModule.tap("MyPlugin", (module) => {

491

moduleSet.add(module);

492

});

493

494

// Efficient membership testing

495

if (moduleSet.has(targetModule)) {

496

console.log("Module is in the set");

497

}

498

499

// Convert to regular set when needed

500

const regularSet = moduleSet.toSet();

501

```

502

503

### Boolean Matching Compiler

504

505

Compiles boolean expressions for efficient module and resource matching.

506

507

```javascript { .api }

508

/**

509

* Compile boolean matcher expression

510

* @param str - Boolean expression string

511

* @returns Compiled matcher function

512

*/

513

function compileBooleanMatcher(str: string): BooleanMatcher;

514

515

/**

516

* Compiled boolean matcher function

517

* @param input - Input string to test

518

* @returns True if input matches expression

519

*/

520

type BooleanMatcher = (input: string) => boolean;

521

522

/**

523

* Parse boolean expression into AST

524

* @param str - Expression string

525

* @returns Parsed AST

526

*/

527

function parseBooleanExpression(str: string): BooleanExpressionNode;

528

529

/**

530

* Optimize boolean expression for performance

531

* @param expression - Boolean expression AST

532

* @returns Optimized expression

533

*/

534

function optimizeBooleanExpression(expression: BooleanExpressionNode): BooleanExpressionNode;

535

536

interface BooleanExpressionNode {

537

type: "literal" | "and" | "or" | "not" | "identifier";

538

value?: string | boolean;

539

left?: BooleanExpressionNode;

540

right?: BooleanExpressionNode;

541

expression?: BooleanExpressionNode;

542

}

543

```

544

545

**Usage Examples:**

546

547

```javascript

548

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

549

550

// Compile matcher for conditional builds

551

const matcher = compileBooleanMatcher("production && !development");

552

553

// Test against build conditions

554

const isMatch = matcher("production"); // true

555

const isMatchDev = matcher("development"); // false

556

557

// Complex expressions

558

const complexMatcher = compileBooleanMatcher("(web || electron) && !node");

559

console.log(complexMatcher("web")); // true

560

console.log(complexMatcher("node")); // false

561

```

562

563

### Template System

564

565

Code generation template utilities for webpack's output system.

566

567

```javascript { .api }

568

class Template {

569

/**

570

* Indent multiline strings

571

* @param str - String to indent

572

* @param prefix - Indentation prefix (default: "\t")

573

* @returns Indented string

574

*/

575

static indent(str: string | string[], prefix?: string): string;

576

577

/**

578

* Convert string to identifier

579

* @param str - String to convert

580

* @returns Valid JavaScript identifier

581

*/

582

static toIdentifier(str: string): string;

583

584

/**

585

* Convert string to comment

586

* @param str - String to convert

587

* @returns Valid JavaScript comment

588

*/

589

static toComment(str: string): string;

590

591

/**

592

* Convert to normal comment

593

* @param str - String to convert

594

* @returns Normal comment string

595

*/

596

static toNormalComment(str: string): string;

597

598

/**

599

* Convert string to path

600

* @param str - String to convert

601

* @returns Path string

602

*/

603

static toPath(str: string): string;

604

605

/**

606

* Generate number to identifier mapping

607

* @param n - Number to convert

608

* @returns Short identifier string

609

*/

610

static numberToIdentifier(n: number): string;

611

612

/**

613

* Generate identifier to number mapping

614

* @param identifier - Identifier string

615

* @returns Corresponding number

616

*/

617

static identifierToNumber(identifier: string): number;

618

619

/**

620

* Escape string for JavaScript

621

* @param str - String to escape

622

* @returns Escaped string

623

*/

624

static quoteMeta(str: string): string;

625

626

/**

627

* Join array with separators

628

* @param array - Array to join

629

* @param separator - Separator string

630

* @returns Joined string

631

*/

632

static asString(array: (string | number)[], separator?: string): string;

633

634

/**

635

* Prefix each line with given string

636

* @param str - String to process

637

* @param prefix - Prefix for each line

638

* @returns Prefixed string

639

*/

640

static prefix(str: string, prefix: string): string;

641

642

/**

643

* Create property access string

644

* @param properties - Property path array

645

* @returns Property access code

646

*/

647

static property(properties: (string | number)[]): string;

648

}

649

```

650

651

**Usage Examples:**

652

653

```javascript

654

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

655

656

// Generate indented code

657

const code = Template.indent([

658

"function myFunction() {",

659

Template.indent("return 'hello';"),

660

"}"

661

]);

662

663

// Convert to valid identifier

664

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

665

666

// Generate property access

667

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

668

669

// Create comments

670

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

671

672

// Escape strings

673

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

674

```

675

676

### Statistics Classes

677

678

Compilation statistics and information management.

679

680

```javascript { .api }

681

class Stats {

682

/** Associated compilation */

683

compilation: Compilation;

684

685

/**

686

* Constructor for Stats

687

* @param compilation - Compilation instance

688

*/

689

constructor(compilation: Compilation);

690

691

/**

692

* Check if compilation has errors

693

* @returns True if errors exist

694

*/

695

hasErrors(): boolean;

696

697

/**

698

* Check if compilation has warnings

699

* @returns True if warnings exist

700

*/

701

hasWarnings(): boolean;

702

703

/**

704

* Convert stats to JSON

705

* @param options - Stats options

706

* @returns JSON representation

707

*/

708

toJson(options?: StatsOptions | string): StatsCompilation;

709

710

/**

711

* Convert stats to string

712

* @param options - Stats options

713

* @returns Formatted string

714

*/

715

toString(options?: StatsOptions | string): string;

716

}

717

718

class MultiStats {

719

/** Array of child stats */

720

stats: Stats[];

721

722

/**

723

* Constructor for MultiStats

724

* @param stats - Array of Stats instances

725

*/

726

constructor(stats: Stats[]);

727

728

/**

729

* Check if any compilation has errors

730

* @returns True if any errors exist

731

*/

732

hasErrors(): boolean;

733

734

/**

735

* Check if any compilation has warnings

736

* @returns True if any warnings exist

737

*/

738

hasWarnings(): boolean;

739

740

/**

741

* Convert multi-stats to JSON

742

* @param options - Stats options

743

* @returns JSON representation with children array

744

*/

745

toJson(options?: StatsOptions | string): { children: StatsCompilation[] };

746

747

/**

748

* Convert multi-stats to string

749

* @param options - Stats options

750

* @returns Formatted string representation

751

*/

752

toString(options?: StatsOptions | string): string;

753

}

754

755

interface StatsOptions {

756

/** Include asset information */

757

assets?: boolean;

758

/** Include chunk information */

759

chunks?: boolean;

760

/** Include module information */

761

modules?: boolean;

762

/** Include reasons for including modules */

763

reasons?: boolean;

764

/** Include source code of modules */

765

source?: boolean;

766

/** Include error details */

767

errorDetails?: boolean;

768

/** Maximum number of modules to show */

769

maxModules?: number;

770

/** Include colors in output */

771

colors?: boolean;

772

/** Include performance hints */

773

performance?: boolean;

774

/** Include timing information */

775

timings?: boolean;

776

/** Include built at timestamp */

777

builtAt?: boolean;

778

/** Include version information */

779

version?: boolean;

780

/** Include hash information */

781

hash?: boolean;

782

/** Include public path */

783

publicPath?: boolean;

784

/** Preset configurations */

785

preset?: "errors-only" | "errors-warnings" | "minimal" | "normal" | "verbose";

786

}

787

```

788

789

**Usage Examples:**

790

791

```javascript

792

const webpack = require("webpack");

793

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

794

795

webpack(config, (err, stats) => {

796

if (err || stats.hasErrors()) {

797

console.error("Build failed!");

798

if (stats) {

799

console.error(stats.toString("errors-only"));

800

}

801

return;

802

}

803

804

// Success - show build info

805

console.log(stats.toString({

806

colors: true,

807

chunks: false,

808

modules: false,

809

assets: true

810

}));

811

812

// Get detailed JSON stats

813

const jsonStats = stats.toJson("verbose");

814

console.log(`Build completed in ${jsonStats.time}ms`);

815

});

816

```

817

818

### Caching System

819

820

Webpack's caching infrastructure for build performance optimization.

821

822

```javascript { .api }

823

class Cache {

824

/**

825

* Constructor for Cache

826

* @param options - Cache options

827

*/

828

constructor(options: CacheOptions);

829

830

/**

831

* Get cache item

832

* @param identifier - Cache key

833

* @param etag - Entity tag for cache validation

834

* @param callback - Callback with cached value

835

*/

836

get<T>(

837

identifier: string,

838

etag: string | null,

839

callback: (err: Error | null, result: T | null) => void

840

): void;

841

842

/**

843

* Store cache item

844

* @param identifier - Cache key

845

* @param etag - Entity tag for cache validation

846

* @param data - Data to cache

847

* @param callback - Completion callback

848

*/

849

store<T>(

850

identifier: string,

851

etag: string | null,

852

data: T,

853

callback: (err?: Error) => void

854

): void;

855

856

/**

857

* Store build dependencies

858

* @param dependencies - Build dependencies

859

* @param callback - Completion callback

860

*/

861

storeBuildDependencies(

862

dependencies: Iterable<string>,

863

callback: (err?: Error) => void

864

): void;

865

866

/**

867

* Begin idle period

868

* @param callback - Completion callback

869

*/

870

beginIdle(callback?: () => void): void;

871

872

/**

873

* End idle period

874

* @param callback - Completion callback

875

*/

876

endIdle(callback?: (err?: Error) => void): void;

877

878

/**

879

* Shutdown cache

880

* @param callback - Completion callback

881

*/

882

shutdown(callback?: (err?: Error) => void): void;

883

}

884

885

class CacheFacade {

886

/**

887

* Constructor for CacheFacade

888

* @param cache - Underlying cache instance

889

* @param name - Cache name/namespace

890

* @param defaultTtl - Default TTL in milliseconds

891

*/

892

constructor(cache: Cache, name: string, defaultTtl?: number);

893

894

/**

895

* Get item with promise interface

896

* @param identifier - Cache key

897

* @param etag - Entity tag for validation

898

* @returns Promise with cached value

899

*/

900

getPromise<T>(identifier: string, etag?: string | null): Promise<T | null>;

901

902

/**

903

* Store item with promise interface

904

* @param identifier - Cache key

905

* @param etag - Entity tag for validation

906

* @param data - Data to cache

907

* @returns Promise for completion

908

*/

909

storePromise<T>(identifier: string, etag: string | null, data: T): Promise<void>;

910

911

/**

912

* Provide cached or computed value

913

* @param identifier - Cache key

914

* @param etag - Entity tag for validation

915

* @param computer - Function to compute value if not cached

916

* @returns Promise with value

917

*/

918

provide<T>(

919

identifier: string,

920

etag: string | null,

921

computer: () => T | Promise<T>

922

): Promise<T>;

923

}

924

925

interface CacheOptions {

926

/** Cache type */

927

type?: "memory" | "filesystem";

928

/** Cache directory for filesystem cache */

929

cacheDirectory?: string;

930

/** Build dependencies */

931

buildDependencies?: Record<string, string[]>;

932

/** Cache name */

933

name?: string;

934

/** Cache version */

935

version?: string;

936

/** Maximum age in milliseconds */

937

maxAge?: number;

938

/** Maximum memory usage */

939

maxMemoryUsage?: number;

940

/** Compression */

941

compression?: false | "gzip" | "brotli";

942

}

943

```

944

945

**Usage Examples:**

946

947

```javascript

948

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

949

950

// Create cache with filesystem backend

951

const cache = new Cache({

952

type: "filesystem",

953

cacheDirectory: "./node_modules/.cache/webpack",

954

buildDependencies: {

955

config: ["webpack.config.js"],

956

code: ["src/**"]

957

}

958

});

959

960

// Create facade for specific cache namespace

961

const moduleCache = new CacheFacade(cache, "modules", 1000 * 60 * 60); // 1 hour TTL

962

963

// Cache expensive computation

964

const result = await moduleCache.provide(

965

"my-module-key",

966

"etag-12345",

967

async () => {

968

// Expensive computation here

969

return await processModule(moduleSource);

970

}

971

);

972

973

// Direct cache operations

974

moduleCache.storePromise("processed-module", "v1", processedData);

975

const cached = await moduleCache.getPromise("processed-module", "v1");

976

```

977

978

### Error Handling

979

980

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

981

982

```javascript { .api }

983

class WebpackError extends Error {

984

/** Error name */

985

name: string;

986

987

/** Error message */

988

message: string;

989

990

/** Error details */

991

details?: string;

992

993

/** Module that caused the error */

994

module?: Module;

995

996

/** Location in source where error occurred */

997

loc?: SourceLocation;

998

999

/** Hide error stack trace */

1000

hideStack?: boolean;

1001

1002

/** Error chunk */

1003

chunk?: Chunk;

1004

1005

/** Error file */

1006

file?: string;

1007

1008

/**

1009

* Constructor for WebpackError

1010

* @param message - Error message

1011

* @param module - Associated module

1012

*/

1013

constructor(message?: string, module?: Module);

1014

1015

/**

1016

* Serialize error for caching

1017

* @param context - Serialization context

1018

* @returns Serialized error data

1019

*/

1020

serialize(context: SerializationContext): any;

1021

1022

/**

1023

* Deserialize error from cache

1024

* @param context - Serialization context

1025

* @returns WebpackError instance

1026

*/

1027

static deserialize(context: SerializationContext): WebpackError;

1028

}

1029

1030

class ModuleError extends WebpackError {

1031

/** Module that caused the error */

1032

module: Module;

1033

1034

/**

1035

* Constructor for ModuleError

1036

* @param message - Error message

1037

* @param module - Module that caused error

1038

*/

1039

constructor(message: string, module: Module);

1040

}

1041

1042

class ModuleWarning extends WebpackError {

1043

/** Module that caused the warning */

1044

module: Module;

1045

1046

/**

1047

* Constructor for ModuleWarning

1048

* @param message - Warning message

1049

* @param module - Module that caused warning

1050

*/

1051

constructor(message: string, module: Module);

1052

}

1053

1054

class ValidationError extends Error {

1055

/** Validation errors array */

1056

errors: ValidationErrorInfo[];

1057

1058

/**

1059

* Constructor for ValidationError

1060

* @param errors - Array of validation errors

1061

* @param schema - Schema that was validated against

1062

* @param configuration - Configuration that failed validation

1063

*/

1064

constructor(

1065

errors: ValidationErrorInfo[],

1066

schema: any,

1067

configuration: any

1068

);

1069

}

1070

1071

interface ValidationErrorInfo {

1072

/** Property path that failed validation */

1073

dataPath: string;

1074

/** Schema path */

1075

schemaPath: string;

1076

/** Error keyword */

1077

keyword: string;

1078

/** Parameters for the error */

1079

params: Record<string, any>;

1080

/** Error message */

1081

message?: string;

1082

}

1083

1084

interface SourceLocation {

1085

/** Line number (1-based) */

1086

line: number;

1087

/** Column number (0-based) */

1088

column: number;

1089

/** Character index */

1090

index?: number;

1091

}

1092

```

1093

1094

**Usage Examples:**

1095

1096

```javascript

1097

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

1098

1099

// Create custom webpack error

1100

class CustomBuildError extends WebpackError {

1101

constructor(message, module) {

1102

super(message, module);

1103

this.name = "CustomBuildError";

1104

}

1105

}

1106

1107

// Throw module-specific error

1108

if (moduleHasIssue) {

1109

throw new ModuleError("Module processing failed", module);

1110

}

1111

1112

// Handle validation errors

1113

try {

1114

validateConfiguration(config);

1115

} catch (error) {

1116

if (error instanceof ValidationError) {

1117

console.error("Configuration validation failed:");

1118

error.errors.forEach(err => {

1119

console.error(` ${err.dataPath}: ${err.message}`);

1120

});

1121

}

1122

}

1123

```

1124

1125

### Module Filename Utilities

1126

1127

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

1128

1129

```javascript { .api }

1130

/**

1131

* Module filename helper utilities

1132

*/

1133

interface ModuleFilenameHelpers {

1134

/**

1135

* Create filename template function

1136

* @param template - Filename template string

1137

* @param options - Template options

1138

* @returns Function that generates filenames

1139

*/

1140

createFilename(

1141

template: string | Function,

1142

options?: FilenameTemplateOptions

1143

): (pathData: PathData) => string;

1144

1145

/**

1146

* Replace path variables in template

1147

* @param template - Template string with variables

1148

* @param pathData - Data for variable replacement

1149

* @param assetInfo - Asset information

1150

* @returns Resolved template string

1151

*/

1152

replaceDuplicates(

1153

template: string,

1154

pathData: PathData,

1155

assetInfo?: AssetInfo

1156

): string;

1157

1158

/**

1159

* Create filter function from test patterns

1160

* @param tests - Test patterns (string, RegExp, or array)

1161

* @returns Filter function

1162

*/

1163

matchPart(tests: TestPatterns): (filename: string) => boolean;

1164

1165

/**

1166

* Create object filter function

1167

* @param tests - Test patterns for object properties

1168

* @returns Object filter function

1169

*/

1170

matchObject(tests: Record<string, TestPatterns>): (obj: Record<string, any>) => boolean;

1171

1172

/**

1173

* Get absolute filename from module

1174

* @param module - Module instance

1175

* @returns Absolute filename or empty string

1176

*/

1177

absolutify(module: Module): string;

1178

1179

/**

1180

* Shorten absolute paths for display

1181

* @param filename - Absolute filename

1182

* @param context - Base context path

1183

* @returns Shortened relative path

1184

*/

1185

contextify(filename: string, context: string): string;

1186

}

1187

1188

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

1189

1190

interface PathData {

1191

/** Chunk information */

1192

chunk?: Chunk;

1193

/** Module information */

1194

module?: Module;

1195

/** Hash information */

1196

hash?: string;

1197

/** Content hash information */

1198

contenthash?: string;

1199

/** Chunk hash information */

1200

chunkhash?: string;

1201

/** Filename without query/fragment */

1202

filename?: string;

1203

/** Base name without extension */

1204

basename?: string;

1205

/** Query string */

1206

query?: string;

1207

/** Fragment identifier */

1208

fragment?: string;

1209

/** File extension */

1210

ext?: string;

1211

/** File path without filename */

1212

path?: string;

1213

}

1214

1215

interface FilenameTemplateOptions {

1216

/** No hash length limit */

1217

noHashLength?: boolean;

1218

/** Context for relative paths */

1219

context?: string;

1220

/** Content hash type */

1221

contenthashType?: string;

1222

/** Hash digest encoding */

1223

hashDigest?: string;

1224

/** Hash digest length */

1225

hashDigestLength?: number;

1226

/** Hash function */

1227

hashFunction?: string;

1228

/** Hash salt */

1229

hashSalt?: string;

1230

}

1231

1232

const ModuleFilenameHelpers: ModuleFilenameHelpers;

1233

```

1234

1235

**Usage Examples:**

1236

1237

```javascript

1238

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

1239

1240

// Create filename template function

1241

const filenameTemplate = ModuleFilenameHelpers.createFilename(

1242

"[name].[contenthash:8].js",

1243

{ hashDigestLength: 8 }

1244

);

1245

1246

// Generate filename from path data

1247

const filename = filenameTemplate({

1248

chunk: myChunk,

1249

hash: "abcdef123456",

1250

contenthash: "xyz789",

1251

basename: "main"

1252

});

1253

1254

// Create filter for matching modules

1255

const testFilter = ModuleFilenameHelpers.matchPart([

1256

/\.js$/,

1257

/\.jsx$/,

1258

"specific-module.js"

1259

]);

1260

1261

// Filter modules

1262

const jsModules = modules.filter(module => {

1263

return testFilter(module.resource || "");

1264

});

1265

1266

// Shorten paths for display

1267

const shortPath = ModuleFilenameHelpers.contextify(

1268

"/full/path/to/project/src/module.js",

1269

"/full/path/to/project"

1270

); // "src/module.js"

1271

```

1272

1273

### Request Shortener

1274

1275

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

1276

1277

```javascript { .api }

1278

class RequestShortener {

1279

/**

1280

* Constructor for RequestShortener

1281

* @param context - Base context directory

1282

* @param associatedObjectForCache - Object for cache association

1283

*/

1284

constructor(context: string, associatedObjectForCache?: any);

1285

1286

/**

1287

* Shorten absolute path relative to context

1288

* @param request - Absolute path to shorten

1289

* @returns Shortened path

1290

*/

1291

shorten(request: string): string;

1292

1293

/**

1294

* Shorten request with custom context

1295

* @param request - Request to shorten

1296

* @param context - Custom context path

1297

* @returns Shortened request

1298

*/

1299

relatify(request: string, context?: string): string;

1300

}

1301

```

1302

1303

**Usage Examples:**

1304

1305

```javascript

1306

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

1307

1308

// Create request shortener for project

1309

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

1310

1311

// Shorten module requests

1312

const shortened = shortener.shorten("/project/root/src/components/Button.js");

1313

// Result: "./src/components/Button.js"

1314

1315

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

1316

// Result: "react/index.js"

1317

1318

// Custom context shortening

1319

const relative = shortener.relatify(

1320

"/project/root/src/utils/helper.js",

1321

"/project/root/src/components"

1322

);

1323

// Result: "../utils/helper.js"

1324

```

1325

1326

### External Dependencies Integration

1327

1328

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

1329

1330

```javascript { .api }

1331

/**

1332

* webpack-sources integration utilities

1333

*/

1334

interface Sources {

1335

/** Raw source without transformation */

1336

RawSource: typeof RawSource;

1337

/** Original source with source map support */

1338

OriginalSource: typeof OriginalSource;

1339

/** Source with replacement capabilities */

1340

ReplaceSource: typeof ReplaceSource;

1341

/** Concatenated source from multiple sources */

1342

ConcatSource: typeof ConcatSource;

1343

/** Prefix source with additional content */

1344

PrefixSource: typeof PrefixSource;

1345

/** Cached source with lazy evaluation */

1346

CachedSource: typeof CachedSource;

1347

/** Size-only source for measurements */

1348

SizeOnlySource: typeof SizeOnlySource;

1349

/** Compatibility source wrapper */

1350

CompatSource: typeof CompatSource;

1351

}

1352

1353

class RawSource {

1354

/**

1355

* Constructor for raw source

1356

* @param value - Source code string or buffer

1357

* @param convertToString - Whether to convert buffer to string

1358

*/

1359

constructor(value: string | Buffer, convertToString?: boolean);

1360

1361

/** Get source content */

1362

source(): string | Buffer;

1363

1364

/** Get source map */

1365

sourceAndMap(options?: SourceMapOptions): { source: string | Buffer; map: SourceMap };

1366

1367

/** Get source size */

1368

size(): number;

1369

1370

/** Update hash with source content */

1371

updateHash(hash: Hash): void;

1372

}

1373

1374

class OriginalSource {

1375

/**

1376

* Constructor for original source with source map

1377

* @param value - Source code

1378

* @param name - Source name/filename

1379

*/

1380

constructor(value: string, name: string);

1381

1382

/** Get source content */

1383

source(): string;

1384

1385

/** Get original source map */

1386

sourceAndMap(options?: SourceMapOptions): { source: string; map: SourceMap };

1387

1388

/** Get source size */

1389

size(): number;

1390

}

1391

1392

class ConcatSource {

1393

/**

1394

* Constructor for concatenated source

1395

* @param sources - Sources to concatenate

1396

*/

1397

constructor(...sources: (Source | string)[]);

1398

1399

/**

1400

* Add source to concatenation

1401

* @param item - Source or string to add

1402

*/

1403

add(item: Source | string): void;

1404

1405

/** Get concatenated source */

1406

source(): string;

1407

1408

/** Get source size */

1409

size(): number;

1410

}

1411

1412

interface SourceMapOptions {

1413

/** Include source content in map */

1414

includeSourcesContent?: boolean;

1415

/** Module identifier */

1416

module?: boolean;

1417

/** Column mappings */

1418

columns?: boolean;

1419

}

1420

1421

const sources: Sources;

1422

```

1423

1424

**Usage Examples:**

1425

1426

```javascript

1427

const { sources } = require("webpack");

1428

const { RawSource, ConcatSource, OriginalSource } = sources;

1429

1430

// Create raw source

1431

const moduleSource = new RawSource('console.log("Hello World");');

1432

1433

// Concatenate multiple sources

1434

const bundleSource = new ConcatSource(

1435

'(function() {\n',

1436

new RawSource('var exports = {};\n'),

1437

moduleSource,

1438

'\nreturn exports;\n',

1439

'})()'

1440

);

1441

1442

// Original source with source map

1443

const originalSource = new OriginalSource(

1444

'const message = "Hello";\nconsole.log(message);',

1445

'original-file.js'

1446

);

1447

1448

// Get combined source

1449

const finalSource = bundleSource.source();

1450

const sourceMap = originalSource.sourceAndMap();

1451

```

1452

1453

### CLI Interface Utilities

1454

1455

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

1456

1457

```javascript { .api }

1458

/**

1459

* CLI interface utilities

1460

*/

1461

interface CLIUtils {

1462

/**

1463

* Parse CLI arguments

1464

* @param args - Command line arguments array

1465

* @returns Parsed options object

1466

*/

1467

parseArgs(args: string[]): CLIOptions;

1468

1469

/**

1470

* Process webpack configuration from CLI

1471

* @param options - CLI options

1472

* @returns Webpack configuration

1473

*/

1474

processConfigOptions(options: CLIOptions): Configuration;

1475

1476

/**

1477

* Setup compiler with CLI options

1478

* @param config - Webpack configuration

1479

* @param options - CLI options

1480

* @returns Configured compiler

1481

*/

1482

setupCompiler(config: Configuration, options: CLIOptions): Compiler;

1483

1484

/**

1485

* Run webpack with CLI options

1486

* @param compiler - Webpack compiler

1487

* @param options - CLI options

1488

* @param callback - Completion callback

1489

*/

1490

runCompiler(

1491

compiler: Compiler,

1492

options: CLIOptions,

1493

callback: (err: Error | null, stats?: Stats) => void

1494

): void;

1495

1496

/**

1497

* Format stats output for CLI

1498

* @param stats - Compilation stats

1499

* @param options - Format options

1500

* @returns Formatted output string

1501

*/

1502

formatStats(stats: Stats, options?: StatsFormatOptions): string;

1503

1504

/**

1505

* Handle CLI errors and exit codes

1506

* @param error - Error to handle

1507

* @param stats - Optional stats for context

1508

* @returns Exit code

1509

*/

1510

handleError(error: Error | null, stats?: Stats): number;

1511

}

1512

1513

interface CLIOptions {

1514

/** Entry point files */

1515

entry?: string | string[];

1516

/** Output configuration */

1517

output?: string;

1518

/** Build mode */

1519

mode?: "development" | "production" | "none";

1520

/** Configuration file path */

1521

config?: string;

1522

/** Environment variables */

1523

env?: Record<string, any>;

1524

/** Watch mode */

1525

watch?: boolean;

1526

/** Development server */

1527

devServer?: boolean;

1528

/** Stats output format */

1529

stats?: string | StatsOptions;

1530

/** Colors in output */

1531

color?: boolean;

1532

/** Progress reporting */

1533

progress?: boolean;

1534

/** Bail on first error */

1535

bail?: boolean;

1536

/** Profile performance */

1537

profile?: boolean;

1538

/** JSON output */

1539

json?: boolean | string;

1540

}

1541

1542

interface StatsFormatOptions {

1543

/** Include colors */

1544

colors?: boolean;

1545

/** Show cached modules */

1546

cached?: boolean;

1547

/** Show cached assets */

1548

cachedAssets?: boolean;

1549

/** Exclude modules */

1550

exclude?: string | RegExp | Array<string | RegExp>;

1551

/** Maximum modules to display */

1552

maxModules?: number;

1553

/** Show reasons */

1554

reasons?: boolean;

1555

/** Show depth */

1556

depth?: boolean;

1557

/** Show used exports */

1558

usedExports?: boolean;

1559

/** Show provided exports */

1560

providedExports?: boolean;

1561

}

1562

1563

const cli: CLIUtils;

1564

```

1565

1566

**Usage Examples:**

1567

1568

```javascript

1569

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

1570

1571

// Parse command line arguments

1572

const options = cli.parseArgs(process.argv.slice(2));

1573

1574

// Process configuration from CLI options

1575

const config = cli.processConfigOptions(options);

1576

1577

// Setup and run compiler

1578

const compiler = cli.setupCompiler(config, options);

1579

1580

cli.runCompiler(compiler, options, (err, stats) => {

1581

if (err) {

1582

const exitCode = cli.handleError(err, stats);

1583

process.exit(exitCode);

1584

}

1585

1586

// Format and display stats

1587

const output = cli.formatStats(stats, {

1588

colors: options.color,

1589

cached: false,

1590

reasons: options.verbose

1591

});

1592

1593

console.log(output);

1594

});

1595

1596

// Handle different output formats

1597

if (options.json) {

1598

const jsonOutput = stats.toJson();

1599

if (typeof options.json === 'string') {

1600

require('fs').writeFileSync(options.json, JSON.stringify(jsonOutput, null, 2));

1601

} else {

1602

console.log(JSON.stringify(jsonOutput));

1603

}

1604

}

1605

```

1606

1607

### Runtime Utilities

1608

1609

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

1610

1611

```javascript { .api }

1612

/**

1613

* Runtime utilities for webpack's generated code

1614

*/

1615

const runtime: {

1616

/**

1617

* Get the current runtime

1618

* @returns Runtime identifier

1619

*/

1620

getRuntime(): string | undefined;

1621

1622

/**

1623

* Merge runtime sets

1624

* @param a - First runtime set

1625

* @param b - Second runtime set

1626

* @returns Merged runtime set

1627

*/

1628

mergeRuntime(a: RuntimeSpec | undefined, b: RuntimeSpec | undefined): RuntimeSpec | undefined;

1629

1630

/**

1631

* Subtract runtime from another

1632

* @param a - Base runtime set

1633

* @param b - Runtime set to subtract

1634

* @returns Resulting runtime set

1635

*/

1636

subtractRuntime(a: RuntimeSpec | undefined, b: RuntimeSpec | undefined): RuntimeSpec | undefined;

1637

1638

/**

1639

* Convert runtime to string

1640

* @param runtime - Runtime spec to stringify

1641

* @returns String representation

1642

*/

1643

runtimeToString(runtime: RuntimeSpec): string;

1644

1645

/**

1646

* Get all chunk runtime requirements

1647

* @param chunks - Chunks to analyze

1648

* @returns Set of runtime requirements

1649

*/

1650

getChunkRuntimeRequirements(chunks: Iterable<Chunk>): Set<string>;

1651

};

1652

1653

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

1654

```

1655

1656

### Serialization Utilities

1657

1658

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

1659

1660

```javascript { .api }

1661

/**

1662

* Serialization utilities for webpack's caching system

1663

*/

1664

const serialization: {

1665

/**

1666

* Register a serializable class

1667

* @param constructor - Class constructor to register

1668

* @param name - Serialization name

1669

* @param serializer - Custom serializer object

1670

*/

1671

register(constructor: any, name: string, serializer?: ObjectSerializer): void;

1672

1673

/**

1674

* Create a binary serializer for efficient storage

1675

* @returns Binary serializer instance

1676

*/

1677

createBinarySerializer(): BinarySerializer;

1678

1679

/**

1680

* Create a hash serializer for content hashing

1681

* @returns Hash serializer instance

1682

*/

1683

createHashSerializer(): HashSerializer;

1684

1685

/**

1686

* Create a file serializer for disk caching

1687

* @param fs - File system to use

1688

* @returns File serializer instance

1689

*/

1690

createFileSerializer(fs: FileSystem): FileSerializer;

1691

};

1692

1693

interface ObjectSerializer {

1694

serialize(obj: any, context: ObjectSerializerContext): void;

1695

deserialize(context: ObjectDeserializerContext): any;

1696

}

1697

1698

interface BinarySerializer {

1699

serialize(obj: any): Buffer;

1700

deserialize(buffer: Buffer): any;

1701

}

1702

```

1703

1704

### Boolean Matcher Utilities

1705

1706

Utilities for creating efficient boolean matching functions from configuration patterns.

1707

1708

```javascript { .api }

1709

/**

1710

* Compile a boolean matcher function from patterns

1711

* @param str - Pattern string or function

1712

* @returns Optimized boolean matcher function

1713

*/

1714

function compileBooleanMatcher(str: string | ((str: string) => boolean)): (str: string) => boolean;

1715

1716

/**

1717

* Create cached boolean matcher for better performance

1718

* @param str - Pattern string or function

1719

* @returns Cached boolean matcher function

1720

*/

1721

function createCachedBooleanMatcher(str: string | ((str: string) => boolean)): (str: string) => boolean;

1722

```

1723

1724

### Webpack Sources Integration

1725

1726

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

1727

1728

```javascript { .api }

1729

/**

1730

* Webpack sources library exports for source manipulation

1731

*/

1732

const sources: {

1733

Source: typeof Source;

1734

RawSource: typeof RawSource;

1735

OriginalSource: typeof OriginalSource;

1736

ReplaceSource: typeof ReplaceSource;

1737

SourceMapSource: typeof SourceMapSource;

1738

ConcatSource: typeof ConcatSource;

1739

PrefixSource: typeof PrefixSource;

1740

CachedSource: typeof CachedSource;

1741

SizeOnlySource: typeof SizeOnlySource;

1742

CompatSource: typeof CompatSource;

1743

};

1744

1745

// Basic source types from webpack-sources

1746

interface Source {

1747

source(): string | Buffer;

1748

buffer(): Buffer;

1749

size(): number;

1750

map(options?: any): Object | null;

1751

sourceAndMap(options?: any): { source: string | Buffer; map: Object | null };

1752

updateHash(hash: Hash): void;

1753

}

1754

1755

class RawSource implements Source {

1756

constructor(source: string | Buffer, convertToString?: boolean);

1757

source(): string | Buffer;

1758

buffer(): Buffer;

1759

size(): number;

1760

map(options?: any): null;

1761

sourceAndMap(options?: any): { source: string | Buffer; map: null };

1762

updateHash(hash: Hash): void;

1763

}

1764

1765

class ConcatSource implements Source {

1766

constructor(...sources: (string | Source)[]);

1767

add(source: string | Source): void;

1768

source(): string;

1769

buffer(): Buffer;

1770

size(): number;

1771

map(options?: any): Object | null;

1772

sourceAndMap(options?: any): { source: string; map: Object | null };

1773

updateHash(hash: Hash): void;

1774

}

1775

```

1776

1777

## Common Types

1778

1779

```javascript { .api }

1780

interface Module {

1781

/** Module identifier */

1782

identifier(): string;

1783

/** Module resource path */

1784

resource?: string;

1785

/** Module type */

1786

type: string;

1787

/** Module source */

1788

source(): Source;

1789

/** Module size */

1790

size(): number;

1791

/** Module hash */

1792

hash?: string;

1793

/** Build info */

1794

buildInfo?: BuildInfo;

1795

/** Build meta */

1796

buildMeta?: BuildMeta;

1797

}

1798

1799

interface Chunk {

1800

/** Chunk identifier */

1801

id: string | number | null;

1802

/** Chunk name */

1803

name?: string;

1804

/** Chunk hash */

1805

hash?: string;

1806

/** Content hash */

1807

contentHash: Record<string, string>;

1808

/** Chunk files */

1809

files: Set<string>;

1810

/** Chunk size */

1811

size(): number;

1812

}

1813

1814

interface ChunkGroup {

1815

/** Chunk group name */

1816

name?: string;

1817

/** Child chunks */

1818

chunks: Chunk[];

1819

/** Parent groups */

1820

parents: Set<ChunkGroup>;

1821

/** Children groups */

1822

children: Set<ChunkGroup>;

1823

}

1824

1825

interface Source {

1826

source(): string | Buffer;

1827

size(): number;

1828

sourceAndMap(options?: any): { source: string | Buffer; map: any };

1829

updateHash(hash: Hash): void;

1830

}

1831

```

1832

1833

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.