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

index.mddocs/

0

# Webpack

1

2

Webpack is a comprehensive module bundler and build tool for JavaScript applications that transforms, bundles, and optimizes various types of assets including JavaScript modules (ES6, CommonJS, AMD), stylesheets, images, and other resources into optimized bundles suitable for web browsers. It provides a powerful plugin system, loader architecture, code splitting, hot module replacement, and production optimization features.

3

4

## Package Information

5

6

- **Package Name**: webpack

7

- **Package Type**: npm

8

- **Language**: JavaScript with TypeScript support

9

- **Installation**: `npm install webpack`

10

11

## Core Imports

12

13

```javascript

14

const webpack = require("webpack");

15

```

16

17

For ES modules:

18

19

```javascript

20

import webpack from "webpack";

21

```

22

23

Individual components can be imported:

24

25

```javascript

26

const {

27

Compiler,

28

Compilation,

29

DefinePlugin,

30

HotModuleReplacementPlugin

31

} = require("webpack");

32

```

33

34

## Basic Usage

35

36

```javascript

37

const webpack = require("webpack");

38

39

// Configuration-based usage

40

const config = {

41

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

42

output: {

43

filename: "bundle.js",

44

path: __dirname + "/dist"

45

},

46

mode: "production"

47

};

48

49

// Callback-style compilation

50

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

51

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

52

console.error(err || stats.toString());

53

return;

54

}

55

console.log("Build successful!");

56

});

57

58

// Programmatic compiler usage

59

const compiler = webpack(config);

60

compiler.run((err, stats) => {

61

if (err) console.error(err);

62

console.log(stats.toString());

63

64

compiler.close((closeErr) => {

65

if (closeErr) console.error(closeErr);

66

});

67

});

68

```

69

70

## Architecture

71

72

Webpack is built around several key architectural components:

73

74

- **Compiler**: Central orchestrator that manages the entire build process and provides a hooks-based plugin system

75

- **Compilation**: Represents a single build process with modules, chunks, and assets

76

- **Module System**: Handles different module types (JavaScript, CSS, assets) with dependency tracking

77

- **Plugin System**: Extensible architecture allowing custom build logic through lifecycle hooks

78

- **Loader System**: Transforms source files during import/require processing

79

- **Runtime**: Generated code that handles module loading, chunk loading, and hot updates in the browser

80

- **Optimization**: Built-in and pluggable optimizations including code splitting, tree shaking, and minification

81

82

## Capabilities

83

84

### Core Compilation System

85

86

Central webpack compilation functionality including the compiler, compilation process, and module management. Essential for all webpack operations.

87

88

```javascript { .api }

89

/**

90

* Main webpack compilation function

91

* @param options - Webpack configuration object or array of configurations

92

* @param callback - Optional callback for handling compilation results

93

* @returns Compiler or MultiCompiler instance

94

*/

95

function webpack(

96

options: Configuration | MultiConfiguration,

97

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

98

): Compiler | MultiCompiler | null;

99

100

interface Configuration {

101

entry?: string | string[] | Entry;

102

output?: Output;

103

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

104

module?: ModuleOptions;

105

plugins?: WebpackPluginInstance[];

106

resolve?: ResolveOptions;

107

optimization?: OptimizationOptions;

108

devtool?: string | false;

109

target?: string | string[];

110

externals?: Externals;

111

// ... additional configuration options

112

}

113

114

class Compiler {

115

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

116

watch(watchOptions: WatchOptions, handler: (err: Error | null, stats?: Stats) => void): Watching;

117

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

118

// ... additional compiler methods

119

}

120

```

121

122

[Core Compilation System](./core-compilation.md)

123

124

### Plugin System

125

126

Comprehensive built-in plugin ecosystem for optimization, development tools, platform support, and custom functionality. Over 60 built-in plugins covering all aspects of the build process.

127

128

```javascript { .api }

129

// Core functionality plugins

130

class DefinePlugin {

131

constructor(definitions: Record<string, any>);

132

}

133

134

class HotModuleReplacementPlugin {

135

constructor(options?: HMROptions);

136

}

137

138

class ProgressPlugin {

139

constructor(options?: ProgressPluginOptions);

140

}

141

142

// Optimization plugins

143

class optimize.SplitChunksPlugin {

144

constructor(options?: SplitChunksOptions);

145

}

146

147

class optimize.ModuleConcatenationPlugin {

148

constructor();

149

}

150

```

151

152

[Plugin System](./plugins.md)

153

154

### Configuration API

155

156

Configuration processing, validation, and default value application. Handles complex configuration normalization and validation.

157

158

```javascript { .api }

159

/**

160

* Validates webpack configuration against schema

161

* @param options - Configuration to validate

162

*/

163

function validate(options: Configuration | MultiConfiguration): void;

164

165

/**

166

* Normalizes webpack configuration

167

* @param options - Raw configuration options

168

* @returns Normalized configuration

169

*/

170

function config.getNormalizedWebpackOptions(options: Configuration): WebpackOptionsNormalized;

171

172

/**

173

* Applies default configuration values

174

* @param options - Normalized configuration

175

* @returns Configuration with defaults applied

176

*/

177

function config.applyWebpackOptionsDefaults(options: WebpackOptionsNormalized): WebpackOptionsNormalized;

178

```

179

180

[Configuration API](./configuration.md)

181

182

### Module System

183

184

Module processing, dependency resolution, and module graph management. Handles JavaScript, CSS, assets, and WebAssembly modules with full dependency tracking.

185

186

```javascript { .api }

187

class Module {

188

// Base module class with common functionality

189

type: string;

190

context: string | null;

191

dependencies: Dependency[];

192

buildInfo: Record<string, any>;

193

}

194

195

class NormalModule extends Module {

196

// Standard file-based modules processed through loaders

197

request: string;

198

resource: string;

199

loaders: any[];

200

}

201

202

class ModuleGraph {

203

// Manages module dependency relationships

204

getModule(dependency: Dependency): Module | null;

205

getConnection(dependency: Dependency): ModuleGraphConnection | null;

206

setResolvedModule(originModule: Module, dependency: Dependency, module: Module): void;

207

}

208

```

209

210

[Module System](./module-system.md)

211

212

### Optimization System

213

214

Built-in optimization features including code splitting, tree shaking, chunk optimization, and production-ready asset generation.

215

216

```javascript { .api }

217

interface OptimizationOptions {

218

minimize?: boolean;

219

minimizer?: WebpackPluginInstance[];

220

splitChunks?: SplitChunksOptions;

221

runtimeChunk?: RuntimeChunkOptions;

222

sideEffects?: boolean;

223

usedExports?: boolean;

224

// ... additional optimization options

225

}

226

227

class optimize.SplitChunksPlugin {

228

constructor(options?: SplitChunksOptions);

229

}

230

231

class optimize.RuntimeChunkPlugin {

232

constructor(options?: RuntimeChunkOptions);

233

}

234

```

235

236

[Optimization System](./optimization.md)

237

238

### Development Tools

239

240

Development-focused features including source maps, hot module replacement, progress reporting, and development server integration.

241

242

```javascript { .api }

243

class HotModuleReplacementPlugin {

244

constructor(options?: HMROptions);

245

}

246

247

class SourceMapDevToolPlugin {

248

constructor(options?: SourceMapDevToolPluginOptions);

249

}

250

251

class ProgressPlugin {

252

constructor(options?: ProgressPluginOptions);

253

}

254

255

interface WatchOptions {

256

aggregateTimeout?: number;

257

poll?: boolean | number;

258

ignored?: string | RegExp | string[];

259

}

260

```

261

262

[Development Tools](./development-tools.md)

263

264

### Runtime System

265

266

Webpack runtime code generation, chunk loading mechanisms, and module resolution at runtime. Includes support for different environments and loading strategies.

267

268

```javascript { .api }

269

const RuntimeGlobals: {

270

require: "__webpack_require__";

271

requireScope: "__webpack_require__.*";

272

exports: "__webpack_exports__";

273

module: "module";

274

// ... additional runtime globals

275

};

276

277

class RuntimeModule {

278

// Base class for runtime code modules

279

name: string;

280

stage: number;

281

generate(): string;

282

}

283

```

284

285

[Runtime System](./runtime-system.md)

286

287

### Utility Functions

288

289

Helper functions and utilities for hashing, serialization, path manipulation, and other common webpack operations.

290

291

```javascript { .api }

292

const util: {

293

createHash(algorithm?: string): Hash;

294

comparators: ComparisonHelpers;

295

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

296

LazySet: typeof LazySet;

297

// ... additional utilities

298

};

299

300

class Stats {

301

// Compilation statistics and information

302

hasErrors(): boolean;

303

hasWarnings(): boolean;

304

toString(options?: StatsOptions): string;

305

toJson(options?: StatsOptions): StatsCompilation;

306

}

307

```

308

309

[Utility Functions](./utilities.md)

310

311

### Validation and Versioning

312

313

Core webpack validation functions and version information.

314

315

```javascript { .api }

316

/**

317

* Validates webpack configuration against JSON schema

318

* @param schema - JSON schema to validate against

319

* @param options - Configuration object to validate

320

* @param options - Additional validation options

321

*/

322

function validateSchema(

323

schema: JSONSchema4 | JSONSchema6 | JSONSchema7,

324

options: any,

325

options?: ValidationErrorConfiguration

326

): void;

327

328

/**

329

* Current webpack version string

330

*/

331

const version: string;

332

```

333

334

### Core Classes and Utilities

335

336

Essential webpack classes and utilities for advanced usage and plugin development.

337

338

```javascript { .api }

339

// Core infrastructure classes

340

class WebpackError extends Error {

341

name: string;

342

message: string;

343

details?: string;

344

origin?: string;

345

dependencies?: Dependency[];

346

}

347

348

class Dependency {

349

type: string;

350

category: string;

351

loc?: SourceLocation;

352

}

353

354

class Cache {

355

// Webpack's caching infrastructure

356

get<T>(identifier: string, etag: string | null, callback: (err?: Error, result?: T) => void): void;

357

store<T>(identifier: string, etag: string | null, data: T, callback: (err?: Error) => void): void;

358

}

359

360

class Chunk {

361

// Represents a chunk in the webpack dependency graph

362

id: string | number | null;

363

name?: string;

364

files: Set<string>;

365

auxiliary: Set<string>;

366

}

367

368

class ChunkGraph {

369

// Manages chunk-module relationships

370

getChunkModules(chunk: Chunk): Module[];

371

getModuleChunks(module: Module): Chunk[];

372

}

373

374

class Template {

375

// Base template functionality for code generation

376

static indent(str: string | string[]): string;

377

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

378

static asString(str: string | string[]): string;

379

}

380

381

// Validation utilities

382

class ValidationError extends Error {

383

constructor(errors: ValidationErrorInstance[], schema: object, configuration: object);

384

errors: ValidationErrorInstance[];

385

schema: object;

386

configuration: object;

387

}

388

```

389

390

## Common Types

391

392

```javascript { .api }

393

type Entry = string | string[] | EntryObject;

394

395

interface EntryObject {

396

[name: string]: string | string[] | EntryDescription;

397

}

398

399

interface Output {

400

filename?: string | ((pathData: PathData) => string);

401

path?: string;

402

publicPath?: string | ((pathData: PathData) => string);

403

library?: LibraryOptions;

404

// ... additional output options

405

}

406

407

interface WebpackPluginInstance {

408

apply(compiler: Compiler): void;

409

}

410

411

type WebpackPluginFunction = (compiler: Compiler) => void;

412

413

interface Stats {

414

hasErrors(): boolean;

415

hasWarnings(): boolean;

416

toString(options?: StatsOptions): string;

417

toJson(options?: StatsOptions): StatsCompilation;

418

}

419

420

interface MultiStats {

421

hasErrors(): boolean;

422

hasWarnings(): boolean;

423

toString(options?: MultiStatsOptions): string;

424

toJson(options?: MultiStatsOptions): { children: StatsCompilation[] };

425

}

426

```

427

428

## Error Handling

429

430

Webpack provides comprehensive error handling through stats objects and callback error parameters:

431

432

```javascript

433

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

434

// Handle compilation errors

435

if (err) {

436

console.error("Fatal webpack error:", err);

437

return;

438

}

439

440

// Handle build errors/warnings

441

if (stats.hasErrors()) {

442

console.error("Build errors:", stats.toString({ errors: true }));

443

}

444

445

if (stats.hasWarnings()) {

446

console.warn("Build warnings:", stats.toString({ warnings: true }));

447

}

448

});

449

```