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

configuration.mddocs/

0

# Configuration API

1

2

Webpack's configuration API provides comprehensive configuration processing, validation, and default value application. It handles complex configuration normalization, validation against schemas, and application of intelligent defaults based on environment and build mode.

3

4

## Capabilities

5

6

### Configuration Validation

7

8

Validates webpack configuration objects against the internal schema to ensure correctness and provide helpful error messages.

9

10

```javascript { .api }

11

/**

12

* Validates webpack configuration against schema

13

* @param options - Configuration object or array of configurations to validate

14

* @throws ValidationError if configuration is invalid

15

*/

16

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

17

18

/**

19

* General schema validation utility for custom schemas

20

* @param schema - JSON schema to validate against

21

* @param options - Object to validate

22

* @param optionsName - Name of the options for error messages

23

* @throws ValidationError if validation fails

24

*/

25

function validateSchema(

26

schema: JSONSchema7,

27

options: any,

28

optionsName: string

29

): void;

30

```

31

32

**Usage Examples:**

33

34

```javascript

35

const webpack = require("webpack");

36

37

try {

38

webpack.validate({

39

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

40

output: {

41

filename: "bundle.js",

42

path: "/invalid/path" // This might trigger validation warnings

43

},

44

mode: "production"

45

});

46

console.log("Configuration is valid!");

47

} catch (error) {

48

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

49

}

50

```

51

52

### Configuration Normalization

53

54

Normalizes raw webpack configuration into a standardized internal format, handling various input formats and shorthand notations.

55

56

```javascript { .api }

57

/**

58

* Normalizes webpack configuration options

59

* @param options - Raw configuration options in any supported format

60

* @returns Normalized configuration with consistent structure

61

*/

62

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

63

```

64

65

**Usage Examples:**

66

67

```javascript

68

const { getNormalizedWebpackOptions } = require("webpack/lib/config/normalization");

69

70

// Normalize shorthand entry format

71

const rawConfig = {

72

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

73

mode: "development"

74

};

75

76

const normalized = getNormalizedWebpackOptions(rawConfig);

77

// normalized.entry is now: { main: { import: ["./src/index.js"] } }

78

```

79

80

### Configuration Defaults

81

82

Applies intelligent default values based on mode, target, and other configuration options.

83

84

```javascript { .api }

85

/**

86

* Applies default configuration values to normalized options

87

* @param options - Normalized webpack options

88

* @returns Configuration with defaults applied

89

*/

90

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

91

```

92

93

**Usage Examples:**

94

95

```javascript

96

const { applyWebpackOptionsDefaults } = require("webpack/lib/config/defaults");

97

const { getNormalizedWebpackOptions } = require("webpack/lib/config/normalization");

98

99

const rawConfig = { entry: "./src/index.js", mode: "production" };

100

const normalized = getNormalizedWebpackOptions(rawConfig);

101

const withDefaults = applyWebpackOptionsDefaults(normalized);

102

103

// withDefaults now includes default optimization settings, output paths, etc.

104

```

105

106

### Main Configuration Interface

107

108

The comprehensive webpack configuration interface supporting all build scenarios from simple applications to complex multi-target builds.

109

110

```javascript { .api }

111

interface Configuration {

112

/** Entry points for the application */

113

entry?: string | string[] | Entry | EntryFunc;

114

115

/** Output configuration for generated bundles */

116

output?: Output;

117

118

/** Build mode affecting defaults and optimizations */

119

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

120

121

/** Module processing configuration */

122

module?: ModuleOptions;

123

124

/** Array of webpack plugins */

125

plugins?: WebpackPluginInstance[];

126

127

/** Module resolution configuration */

128

resolve?: ResolveOptions;

129

130

/** Optimization configuration */

131

optimization?: OptimizationOptions;

132

133

/** Development tool for source maps */

134

devtool?: string | false;

135

136

/** Build target environment */

137

target?: string | string[] | false;

138

139

/** External dependencies configuration */

140

externals?: Externals;

141

142

/** Performance hints and limits */

143

performance?: Performance | false;

144

145

/** Node.js polyfills configuration */

146

node?: Node | false;

147

148

/** Statistics output configuration */

149

stats?: StatsOptions | string | boolean;

150

151

/** Watch mode configuration */

152

watch?: boolean;

153

154

/** Watch options */

155

watchOptions?: WatchOptions;

156

157

/** Development server configuration */

158

devServer?: DevServerOptions;

159

160

/** Caching configuration */

161

cache?: CacheOptions | boolean;

162

163

/** Infrastructure logging configuration */

164

infrastructureLogging?: InfrastructureLogging;

165

166

/** Snapshot configuration for filesystem watching */

167

snapshot?: SnapshotOptions;

168

169

/** Experimental features */

170

experiments?: Experiments;

171

172

/** Context directory for resolving entries */

173

context?: string;

174

175

/** Dependency configuration */

176

dependencies?: string[];

177

178

/** Environment name for conditional configuration */

179

name?: string;

180

181

/** Bail on first error in multi-compiler mode */

182

bail?: boolean;

183

184

/** Profile compilation for performance analysis */

185

profile?: boolean;

186

187

/** Parallelism limit for processing */

188

parallelism?: number;

189

190

/** Record input/output files for persistent caching */

191

recordsPath?: string;

192

recordsInputPath?: string;

193

recordsOutputPath?: string;

194

}

195

196

/** Multi-configuration for parallel builds */

197

type MultiConfiguration = Configuration[];

198

199

/** Function-based configuration for dynamic setups */

200

type ConfigurationFunc = (

201

env: any,

202

argv: any

203

) => Configuration | MultiConfiguration | Promise<Configuration | MultiConfiguration>;

204

```

205

206

### Entry Configurations

207

208

Flexible entry point configuration supporting various application architectures.

209

210

```javascript { .api }

211

/** Entry point configuration types */

212

type Entry = string | string[] | EntryObject | EntryFunc;

213

214

/** Object-based entry configuration for multiple entry points */

215

interface EntryObject {

216

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

217

}

218

219

/** Detailed entry point description */

220

interface EntryDescription {

221

/** Import modules for this entry */

222

import: string | string[];

223

224

/** Runtime chunk name for this entry */

225

runtime?: string | false;

226

227

/** Public path for this entry's assets */

228

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

229

230

/** Base URI for this entry */

231

baseUri?: string;

232

233

/** Chunk loading type for this entry */

234

chunkLoading?: ChunkLoadingType | false;

235

236

/** Async chunks flag */

237

asyncChunks?: boolean;

238

239

/** WASM loading type */

240

wasmLoading?: WasmLoadingType | false;

241

242

/** Entry filename template */

243

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

244

245

/** Library configuration for this entry */

246

library?: LibraryOptions;

247

248

/** Depends on other entries */

249

dependOn?: string | string[];

250

}

251

252

/** Dynamic entry configuration */

253

type EntryFunc = () => Entry | Promise<Entry>;

254

```

255

256

**Usage Examples:**

257

258

```javascript

259

// String entry (single file)

260

module.exports = {

261

entry: "./src/index.js"

262

};

263

264

// Array entry (multiple files, single chunk)

265

module.exports = {

266

entry: ["./src/polyfills.js", "./src/index.js"]

267

};

268

269

// Object entry (multiple named chunks)

270

module.exports = {

271

entry: {

272

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

273

vendor: "./src/vendor.js",

274

admin: "./src/admin/index.js"

275

}

276

};

277

278

// Detailed entry descriptions

279

module.exports = {

280

entry: {

281

main: {

282

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

283

runtime: "main-runtime",

284

dependOn: "shared"

285

},

286

shared: {

287

import: "./src/shared.js",

288

runtime: false // No runtime chunk

289

},

290

admin: {

291

import: "./src/admin/index.js",

292

filename: "admin/[name].[contenthash].js",

293

chunkLoading: "jsonp"

294

}

295

}

296

};

297

298

// Dynamic entry function

299

module.exports = {

300

entry: () => {

301

return {

302

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

303

// Conditionally add entries based on environment

304

...(process.env.NODE_ENV === "development" && {

305

dev: "./src/dev-tools.js"

306

})

307

};

308

}

309

};

310

```

311

312

### Output Configurations

313

314

Comprehensive output configuration for controlling generated bundle characteristics.

315

316

```javascript { .api }

317

interface Output {

318

/** Filename template for entry chunks */

319

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

320

321

/** Output directory path */

322

path?: string;

323

324

/** Public URL path for assets */

325

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

326

327

/** Filename template for non-entry chunks */

328

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

329

330

/** Filename template for async WASM modules */

331

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

332

333

/** Asset module filename template */

334

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

335

336

/** Library configuration for UMD/library builds */

337

library?: LibraryOptions;

338

339

/** Global object name for library builds */

340

globalObject?: string;

341

342

/** Import function name for ESM builds */

343

importFunctionName?: string;

344

345

/** Import meta name for ESM builds */

346

importMetaName?: string;

347

348

/** Clean output directory before build */

349

clean?: boolean | CleanOptions;

350

351

/** Compare before emit to avoid unnecessary writes */

352

compareBeforeEmit?: boolean;

353

354

/** Cross-origin loading configuration */

355

crossOriginLoading?: string | false;

356

357

/** Charset for script tags */

358

charset?: boolean;

359

360

/** Enable/disable source map filename info */

361

sourceMapFilename?: string;

362

363

/** Hotupdate main filename */

364

hotUpdateMainFilename?: string;

365

366

/** Hotupdate chunk filename */

367

hotUpdateChunkFilename?: string;

368

369

/** Script type for entry scripts */

370

scriptType?: "text/javascript" | "module" | false;

371

372

/** Unique name for HMR */

373

uniqueName?: string;

374

375

/** Chunk loading global name */

376

chunkLoadingGlobal?: string;

377

378

/** Enable trusted types policy */

379

trustedTypes?: TrustedTypesOptions | true;

380

381

/** Hash function for content hashing */

382

hashFunction?: string | typeof Hash;

383

384

/** Hash digest type */

385

hashDigest?: string;

386

387

/** Hash digest length */

388

hashDigestLength?: number;

389

390

/** Hash salt */

391

hashSalt?: string;

392

393

/** Strict module exception handling */

394

strictModuleExceptionHandling?: boolean;

395

396

/** Strict module error handling */

397

strictModuleErrorHandling?: boolean;

398

399

/** Module loading type */

400

module?: boolean;

401

402

/** Environment configuration */

403

environment?: Environment;

404

405

/** IIFE (Immediately Invoked Function Expression) wrapper */

406

iife?: boolean;

407

}

408

409

/** Library output configuration */

410

interface LibraryOptions {

411

/** Library name */

412

name?: string | string[] | LibraryName;

413

414

/** Library type (UMD, CommonJS, etc.) */

415

type?: LibraryType;

416

417

/** Export property to expose */

418

export?: string | string[];

419

420

/** UMD named define */

421

umdNamedDefine?: boolean;

422

423

/** Auxiliary comment */

424

auxiliaryComment?: string | LibraryAuxiliaryComment;

425

}

426

```

427

428

**Usage Examples:**

429

430

```javascript

431

module.exports = {

432

output: {

433

// Basic filename with content hash

434

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

435

436

// Output to dist directory

437

path: path.resolve(__dirname, "dist"),

438

439

// Public path for CDN deployment

440

publicPath: "https://cdn.example.com/assets/",

441

442

// Chunk filename pattern

443

chunkFilename: "[name].[contenthash].chunk.js",

444

445

// Asset filename pattern

446

assetModuleFilename: "assets/[name].[hash][ext]",

447

448

// Clean output directory

449

clean: true

450

}

451

};

452

453

// Library build configuration

454

module.exports = {

455

output: {

456

filename: "my-library.js",

457

path: path.resolve(__dirname, "dist"),

458

library: {

459

name: "MyLibrary",

460

type: "umd"

461

},

462

globalObject: "this"

463

}

464

};

465

466

// Dynamic public path

467

module.exports = {

468

output: {

469

filename: "[name].js",

470

publicPath: (pathData) => {

471

return process.env.NODE_ENV === "production"

472

? "/prod-assets/"

473

: "/dev-assets/";

474

}

475

}

476

};

477

```

478

479

### Module Configurations

480

481

Module processing configuration including loaders, parsers, and generators.

482

483

```javascript { .api }

484

interface ModuleOptions {

485

/** Rules for processing different file types */

486

rules?: RuleSetRule[];

487

488

/** No parsing rules */

489

noParse?: string | RegExp | ((content: string) => boolean) | Array<string | RegExp | ((content: string) => boolean)>;

490

491

/** Unknown context request handling */

492

unknownContextRequest?: string;

493

494

/** Unknown context recursive flag */

495

unknownContextRecursive?: boolean;

496

497

/** Unknown context regexp */

498

unknownContextRegExp?: RegExp;

499

500

/** Unknown context critical flag */

501

unknownContextCritical?: boolean;

502

503

/** Expression context request handling */

504

exprContextRequest?: string;

505

506

/** Expression context recursive flag */

507

exprContextRecursive?: boolean;

508

509

/** Expression context regexp */

510

exprContextRegExp?: RegExp;

511

512

/** Expression context critical flag */

513

exprContextCritical?: boolean;

514

515

/** Wrapped context request handling */

516

wrappedContextRequest?: string;

517

518

/** Wrapped context recursive flag */

519

wrappedContextRecursive?: boolean;

520

521

/** Wrapped context regexp */

522

wrappedContextRegExp?: RegExp;

523

524

/** Wrapped context critical flag */

525

wrappedContextCritical?: boolean;

526

527

/** Strict export presence */

528

strictExportPresence?: boolean;

529

530

/** Strict this context on imports */

531

strictThisContextOnImports?: boolean;

532

533

/** Unsafe cache for module processing */

534

unsafeCache?: boolean | ((module: Module) => boolean);

535

536

/** Default rules applied to all modules */

537

defaultRules?: RuleSetRule[];

538

539

/** Parser options by module type */

540

parser?: ParserOptionsByModuleType;

541

542

/** Generator options by module type */

543

generator?: GeneratorOptionsByModuleType;

544

}

545

546

/** Rule for processing modules */

547

interface RuleSetRule {

548

/** Test condition for matching files */

549

test?: RuleSetCondition;

550

551

/** Include condition */

552

include?: RuleSetCondition;

553

554

/** Exclude condition */

555

exclude?: RuleSetCondition;

556

557

/** Resource condition (combines test/include/exclude) */

558

resource?: RuleSetCondition;

559

560

/** Issuer condition (module that imports this) */

561

issuer?: RuleSetCondition;

562

563

/** Dependency type condition */

564

dependency?: RuleSetCondition;

565

566

/** Module layer */

567

layer?: string;

568

569

/** Loaders to apply */

570

use?: RuleSetUse;

571

572

/** Alias for use */

573

loader?: string;

574

575

/** Options for single loader */

576

options?: any;

577

578

/** Module type override */

579

type?: string;

580

581

/** Parser options for this rule */

582

parser?: ParserOptions;

583

584

/** Generator options for this rule */

585

generator?: GeneratorOptions;

586

587

/** Resource fragment condition */

588

resourceFragment?: RuleSetCondition;

589

590

/** Resource query condition */

591

resourceQuery?: RuleSetCondition;

592

593

/** Resolve configuration for this rule */

594

resolve?: ResolveOptions;

595

596

/** Side effects flag */

597

sideEffects?: boolean;

598

599

/** Nested rules */

600

rules?: RuleSetRule[];

601

602

/** Alternative rules (oneOf) */

603

oneOf?: RuleSetRule[];

604

605

/** Enforcement stage */

606

enforce?: "pre" | "post";

607

608

/** Description for debugging */

609

descriptionData?: { [k: string]: any };

610

611

/** Schema version */

612

schema?: any;

613

614

/** Mimetype condition */

615

mimetype?: RuleSetCondition;

616

}

617

618

/** Use configuration for loaders */

619

type RuleSetUse =

620

| RuleSetUseItem

621

| RuleSetUseItem[]

622

| ((info: UseInfo) => RuleSetUseItem | RuleSetUseItem[]);

623

624

/** Individual loader configuration */

625

interface RuleSetUseItem {

626

/** Loader name or path */

627

loader?: string;

628

629

/** Loader options */

630

options?: any;

631

632

/** Loader identifier */

633

ident?: string;

634

635

/** Type of use item */

636

type?: string;

637

}

638

639

/** Condition types for matching */

640

type RuleSetCondition =

641

| string

642

| RegExp

643

| ((value: string) => boolean)

644

| RuleSetLogicalConditions

645

| RuleSetCondition[];

646

647

interface RuleSetLogicalConditions {

648

/** AND condition */

649

and?: RuleSetCondition[];

650

651

/** OR condition */

652

or?: RuleSetCondition[];

653

654

/** NOT condition */

655

not?: RuleSetCondition;

656

}

657

```

658

659

**Usage Examples:**

660

661

```javascript

662

module.exports = {

663

module: {

664

rules: [

665

// JavaScript/TypeScript files

666

{

667

test: /\.(js|ts|tsx)$/,

668

exclude: /node_modules/,

669

use: [

670

{

671

loader: "babel-loader",

672

options: {

673

presets: ["@babel/preset-env", "@babel/preset-react"]

674

}

675

}

676

]

677

},

678

679

// CSS files with CSS modules

680

{

681

test: /\.css$/,

682

include: path.resolve(__dirname, "src"),

683

use: [

684

"style-loader",

685

{

686

loader: "css-loader",

687

options: {

688

modules: true,

689

localIdentName: "[name]__[local]__[hash:base64:5]"

690

}

691

}

692

]

693

},

694

695

// Images and assets

696

{

697

test: /\.(png|jpg|gif|svg)$/,

698

type: "asset/resource",

699

generator: {

700

filename: "images/[name].[hash][ext]"

701

}

702

},

703

704

// Fonts

705

{

706

test: /\.(woff|woff2|eot|ttf|otf)$/,

707

type: "asset/inline"

708

},

709

710

// Conditional loader based on issuer

711

{

712

test: /\.scss$/,

713

issuer: {

714

and: [/\.js$/, { not: /node_modules/ }]

715

},

716

use: ["style-loader", "css-loader", "sass-loader"]

717

},

718

719

// Dynamic loader configuration

720

{

721

test: /\.js$/,

722

use: (info) => {

723

if (info.resource.includes("legacy")) {

724

return ["babel-loader"];

725

}

726

return ["swc-loader"];

727

}

728

}

729

],

730

731

// Skip parsing for known libraries

732

noParse: /jquery|lodash/,

733

734

// Strict export presence checking

735

strictExportPresence: true

736

}

737

};

738

```

739

740

### Resolve Configurations

741

742

Module resolution configuration for finding and processing imports.

743

744

```javascript { .api }

745

interface ResolveOptions {

746

/** Module resolution algorithm */

747

resolverOptions?: ResolverOptions;

748

749

/** Alias mapping for module names */

750

alias?: AliasOptions;

751

752

/** Fallback mapping */

753

fallback?: AliasOptions;

754

755

/** Module directories to search */

756

modules?: string[];

757

758

/** File extensions to try */

759

extensions?: string[];

760

761

/** Main fields to check in package.json */

762

mainFields?: string[];

763

764

/** Main files to look for */

765

mainFiles?: string[];

766

767

/** Description files to read */

768

descriptionFiles?: string[];

769

770

/** Enforce extension requirement */

771

enforceExtension?: boolean;

772

773

/** Exports fields to use */

774

exportsFields?: string[];

775

776

/** Imports fields to use */

777

importsFields?: string[];

778

779

/** Condition names for exports/imports */

780

conditionNames?: string[];

781

782

/** Symbol links handling */

783

symlinks?: boolean;

784

785

/** Cache resolve results */

786

cache?: boolean;

787

788

/** Plugins for custom resolution */

789

plugins?: ResolvePluginInstance[];

790

791

/** Prefer relative paths */

792

preferRelative?: boolean;

793

794

/** Prefer absolute paths */

795

preferAbsolute?: boolean;

796

797

/** Restrictions on resolved paths */

798

restrictions?: (string | RegExp)[];

799

800

/** Roots for absolute resolution */

801

roots?: string[];

802

803

/** Unsafe cache for performance */

804

unsafeCache?: boolean | object;

805

806

/** Full specified flag */

807

fullySpecified?: boolean;

808

809

/** By dependency type resolution */

810

byDependency?: { [k: string]: ResolveOptions };

811

}

812

813

/** Alias configuration */

814

type AliasOptions =

815

| { [key: string]: string | false | string[] }

816

| AliasOption[];

817

818

interface AliasOption {

819

/** Alias name */

820

name: string;

821

822

/** Alias target */

823

alias: string | false | string[];

824

825

/** Only replace if it's the exact match */

826

onlyModule?: boolean;

827

}

828

```

829

830

**Usage Examples:**

831

832

```javascript

833

module.exports = {

834

resolve: {

835

// File extensions to resolve automatically

836

extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],

837

838

// Alias for shorter imports

839

alias: {

840

"@": path.resolve(__dirname, "src"),

841

"@components": path.resolve(__dirname, "src/components"),

842

"@utils": path.resolve(__dirname, "src/utils"),

843

// Exclude a module

844

"fs": false

845

},

846

847

// Module directories

848

modules: ["node_modules", path.resolve(__dirname, "src")],

849

850

// Main fields for package.json

851

mainFields: ["browser", "module", "main"],

852

853

// Main files to try

854

mainFiles: ["index"],

855

856

// Fallbacks for Node.js modules in browser

857

fallback: {

858

"path": require.resolve("path-browserify"),

859

"fs": false,

860

"crypto": require.resolve("crypto-browserify")

861

},

862

863

// Condition names for exports field

864

conditionNames: ["import", "module", "browser", "default"],

865

866

// By dependency type configuration

867

byDependency: {

868

esm: {

869

fullySpecified: true

870

},

871

commonjs: {

872

fullySpecified: false

873

}

874

}

875

}

876

};

877

```

878

879

### Optimization Configurations

880

881

Advanced optimization settings for production builds and performance.

882

883

```javascript { .api }

884

interface OptimizationOptions {

885

/** Enable/disable minimization */

886

minimize?: boolean;

887

888

/** Minimizer plugins */

889

minimizer?: WebpackPluginInstance[];

890

891

/** Split chunks configuration */

892

splitChunks?: SplitChunksOptions | false;

893

894

/** Runtime chunk configuration */

895

runtimeChunk?: RuntimeChunkOptions;

896

897

/** Bail on first error */

898

emitOnErrors?: boolean;

899

900

/** Module concatenation (scope hoisting) */

901

concatenateModules?: boolean;

902

903

/** Side effects detection */

904

sideEffects?: boolean | "flag";

905

906

/** Used exports detection (tree shaking) */

907

usedExports?: boolean | "global";

908

909

/** Provided exports detection */

910

providedExports?: boolean;

911

912

/** Optimization bailout reasons */

913

flagIncludedChunks?: boolean;

914

915

/** Optimize module IDs */

916

moduleIds?: ModuleIdsType;

917

918

/** Optimize chunk IDs */

919

chunkIds?: ChunkIdsType;

920

921

/** Remove available modules */

922

removeAvailableModules?: boolean;

923

924

/** Remove empty chunks */

925

removeEmptyChunks?: boolean;

926

927

/** Merge duplicate chunks */

928

mergeDuplicateChunks?: boolean;

929

930

/** Mangle webpack runtime */

931

mangleWasmImports?: boolean;

932

933

/** Portables records */

934

portableRecords?: boolean;

935

936

/** Real content hash */

937

realContentHash?: boolean;

938

939

/** Inner graph analysis */

940

innerGraph?: boolean;

941

942

/** Mangle exports */

943

mangleExports?: boolean | "deterministic" | "size";

944

945

/** Node.js environment detection */

946

nodeEnv?: string | false;

947

}

948

949

/** Split chunks configuration */

950

interface SplitChunksOptions {

951

/** Chunks to split */

952

chunks?: "all" | "async" | "initial" | ((chunk: Chunk) => boolean);

953

954

/** Minimum chunk size */

955

minSize?: number;

956

957

/** Minimum remaining size after split */

958

minRemainingSize?: number;

959

960

/** Minimum chunk size for development */

961

minSizeReduction?: number;

962

963

/** Maximum async requests */

964

maxAsyncRequests?: number;

965

966

/** Maximum initial requests */

967

maxInitialRequests?: number;

968

969

/** Enforce size limits */

970

enforceSizeThreshold?: number;

971

972

/** Automatic name generation */

973

automaticNameDelimiter?: string;

974

975

/** Cache groups configuration */

976

cacheGroups?: CacheGroupsOptions;

977

978

/** Default name */

979

name?: string | false | SplitChunksNameFunction;

980

981

/** Filename template */

982

filename?: string | SplitChunksFilenameFunction;

983

984

/** Hide path info */

985

hidePathInfo?: boolean;

986

987

/** Maximum size */

988

maxSize?: number;

989

990

/** Maximum async size */

991

maxAsyncSize?: number;

992

993

/** Maximum initial size */

994

maxInitialSize?: number;

995

996

/** Used exports */

997

usedExports?: boolean;

998

}

999

1000

type RuntimeChunkOptions =

1001

| "single"

1002

| "multiple"

1003

| boolean

1004

| { name?: string | RuntimeChunkFunction };

1005

1006

type ModuleIdsType = "natural" | "named" | "deterministic" | "size" | false;

1007

type ChunkIdsType = "natural" | "named" | "deterministic" | "size" | "total-size" | false;

1008

```

1009

1010

**Usage Examples:**

1011

1012

```javascript

1013

module.exports = {

1014

optimization: {

1015

// Enable minimization in production

1016

minimize: true,

1017

1018

// Custom minimizers

1019

minimizer: [

1020

new TerserPlugin({

1021

terserOptions: {

1022

compress: {

1023

drop_console: true

1024

}

1025

}

1026

})

1027

],

1028

1029

// Split chunks configuration

1030

splitChunks: {

1031

chunks: "all",

1032

cacheGroups: {

1033

// Vendor chunk for node_modules

1034

vendor: {

1035

test: /[\\/]node_modules[\\/]/,

1036

name: "vendors",

1037

chunks: "all",

1038

priority: 10

1039

},

1040

1041

// Common chunk for shared modules

1042

common: {

1043

name: "common",

1044

minChunks: 2,

1045

chunks: "all",

1046

priority: 5,

1047

reuseExistingChunk: true

1048

}

1049

}

1050

},

1051

1052

// Extract runtime to separate chunk

1053

runtimeChunk: "single",

1054

1055

// Tree shaking configuration

1056

usedExports: true,

1057

sideEffects: false,

1058

1059

// Module concatenation for better performance

1060

concatenateModules: true,

1061

1062

// Deterministic module IDs for better caching

1063

moduleIds: "deterministic",

1064

chunkIds: "deterministic"

1065

}

1066

};

1067

```

1068

1069

### DevTool Options

1070

1071

Source map generation configuration for debugging support.

1072

1073

```javascript { .api }

1074

/** DevTool configuration for source maps */

1075

type DevTool =

1076

| false

1077

| "eval"

1078

| "eval-cheap-source-map"

1079

| "eval-cheap-module-source-map"

1080

| "eval-source-map"

1081

| "cheap-source-map"

1082

| "cheap-module-source-map"

1083

| "source-map"

1084

| "inline-cheap-source-map"

1085

| "inline-cheap-module-source-map"

1086

| "inline-source-map"

1087

| "eval-nosources-cheap-source-map"

1088

| "eval-nosources-cheap-module-source-map"

1089

| "eval-nosources-source-map"

1090

| "inline-nosources-cheap-source-map"

1091

| "inline-nosources-cheap-module-source-map"

1092

| "inline-nosources-source-map"

1093

| "nosources-cheap-source-map"

1094

| "nosources-cheap-module-source-map"

1095

| "nosources-source-map"

1096

| "hidden-cheap-source-map"

1097

| "hidden-cheap-module-source-map"

1098

| "hidden-source-map"

1099

| "hidden-nosources-cheap-source-map"

1100

| "hidden-nosources-cheap-module-source-map"

1101

| "hidden-nosources-source-map";

1102

```

1103

1104

**Usage Examples:**

1105

1106

```javascript

1107

module.exports = {

1108

// Development: fast rebuilds with good debugging

1109

devtool: process.env.NODE_ENV === "development"

1110

? "eval-cheap-module-source-map"

1111

: "source-map",

1112

1113

// Alternative conditional configuration

1114

devtool: (() => {

1115

if (process.env.NODE_ENV === "production") {

1116

return "source-map"; // High quality for production debugging

1117

}

1118

if (process.env.NODE_ENV === "development") {

1119

return "eval-source-map"; // Fast rebuilds for development

1120

}

1121

return false; // No source maps for other environments

1122

})()

1123

};

1124

```

1125

1126

### Target Options

1127

1128

Build target configuration for different environments and platforms.

1129

1130

```javascript { .api }

1131

/** Target environment configuration */

1132

type Target =

1133

| string

1134

| string[]

1135

| false

1136

| TargetFunction;

1137

1138

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

1139

1140

/** Common target values */

1141

type TargetValues =

1142

| "web" // Web browsers (default)

1143

| "webworker" // Web Workers

1144

| "node" // Node.js

1145

| "async-node" // Node.js with async chunk loading

1146

| "node-webkit" // NW.js

1147

| "nwjs" // NW.js (alias)

1148

| "electron-main" // Electron main process

1149

| "electron-renderer" // Electron renderer process

1150

| "electron-preload" // Electron preload scripts

1151

| "browserslist" // Use browserslist configuration

1152

| "es5" // ES5 compatibility

1153

| "es2015" // ES2015 compatibility

1154

| "es2017" // ES2017 compatibility

1155

| "es2020" // ES2020 compatibility

1156

```

1157

1158

**Usage Examples:**

1159

1160

```javascript

1161

// Single target

1162

module.exports = {

1163

target: "node"

1164

};

1165

1166

// Multiple targets for universal builds

1167

module.exports = {

1168

target: ["web", "es5"]

1169

};

1170

1171

// Browserslist-based targeting

1172

module.exports = {

1173

target: "browserslist"

1174

};

1175

1176

// Function-based target for custom configuration

1177

module.exports = {

1178

target: (compiler) => {

1179

compiler.options.output.globalObject = "this";

1180

}

1181

};

1182

1183

// Environment-specific targets

1184

module.exports = {

1185

target: process.env.ELECTRON_ENV === "main"

1186

? "electron-main"

1187

: "electron-renderer"

1188

};

1189

```

1190

1191

### External Configurations

1192

1193

External dependencies configuration for excluding modules from bundling.

1194

1195

```javascript { .api }

1196

/** External dependencies configuration */

1197

type Externals =

1198

| string

1199

| RegExp

1200

| ExternalItemObjectKnown

1201

| ExternalItemObjectUnknown

1202

| ExternalItemFunctionData

1203

| ExternalItem[]

1204

| (ExternalItemFunctionData | ExternalItemFunctionPromise | ExternalItemValue);

1205

1206

/** External item as object with different module formats */

1207

interface ExternalItemObjectKnown {

1208

/** AMD module format */

1209

amd?: string;

1210

1211

/** CommonJS module format */

1212

commonjs?: string;

1213

1214

/** CommonJS2 module format */

1215

commonjs2?: string;

1216

1217

/** Root (global) variable */

1218

root?: string | string[];

1219

1220

/** Import statement */

1221

import?: string;

1222

1223

/** Variable name */

1224

var?: string;

1225

1226

/** Module format */

1227

module?: string;

1228

1229

/** UMD format */

1230

umd?: string | ExternalItemObjectKnownUmd;

1231

1232

/** JSONP format */

1233

jsonp?: string;

1234

1235

/** System.js format */

1236

system?: string;

1237

1238

/** Promise-based external */

1239

promise?: string;

1240

1241

/** Script source URL */

1242

script?: string | ExternalItemObjectKnownScript;

1243

}

1244

1245

/** Function-based external resolution */

1246

type ExternalItemFunction = (

1247

data: ExternalItemFunctionData,

1248

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

1249

) => void;

1250

1251

interface ExternalItemFunctionData {

1252

/** Module context */

1253

context?: string;

1254

1255

/** Dependency type */

1256

dependencyType?: string;

1257

1258

/** Module request */

1259

request?: string;

1260

1261

/** Context info */

1262

contextInfo?: ModuleInfo;

1263

1264

/** Get resolve function */

1265

getResolve?: (options?: ResolveOptions) => ResolveFunction;

1266

}

1267

```

1268

1269

**Usage Examples:**

1270

1271

```javascript

1272

module.exports = {

1273

// Simple string externals

1274

externals: {

1275

"jquery": "jQuery",

1276

"lodash": "_"

1277

},

1278

1279

// RegExp-based externals

1280

externals: [

1281

/^@company\/.+$/, // Exclude all @company packages

1282

/^aws-sdk/ // Exclude AWS SDK

1283

],

1284

1285

// Multiple formats for different environments

1286

externals: {

1287

"react": {

1288

root: "React",

1289

commonjs2: "react",

1290

commonjs: "react",

1291

amd: "react",

1292

umd: "react"

1293

}

1294

},

1295

1296

// Function-based externals for dynamic resolution

1297

externals: [

1298

(data, callback) => {

1299

// Externalize requests that start with "electron"

1300

if (/^electron/.test(data.request)) {

1301

return callback(null, "commonjs " + data.request);

1302

}

1303

callback();

1304

}

1305

],

1306

1307

// Node.js externals (exclude all node_modules)

1308

externals: [

1309

({ context, request }, callback) => {

1310

if (/^[a-z@][a-z0-9\-\/]*$/.test(request)) {

1311

return callback(null, "commonjs " + request);

1312

}

1313

callback();

1314

}

1315

]

1316

};

1317

```

1318

1319

### Watch Options

1320

1321

File watching configuration for development builds.

1322

1323

```javascript { .api }

1324

interface WatchOptions {

1325

/** Delay before rebuilding after change */

1326

aggregateTimeout?: number;

1327

1328

/** Enable polling for file changes */

1329

poll?: boolean | number;

1330

1331

/** Files/directories to ignore */

1332

ignored?: string | RegExp | string[];

1333

1334

/** Follow symbolic links */

1335

followSymlinks?: boolean;

1336

1337

/** Stdin end triggers exit */

1338

stdin?: boolean;

1339

}

1340

1341

interface Watching {

1342

/** Stop watching */

1343

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

1344

1345

/** Invalidate current build */

1346

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

1347

1348

/** Suspend watching */

1349

suspend(): void;

1350

1351

/** Resume watching */

1352

resume(): void;

1353

}

1354

```

1355

1356

**Usage Examples:**

1357

1358

```javascript

1359

const webpack = require("webpack");

1360

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

1361

1362

const compiler = webpack(config);

1363

1364

// Watch with options

1365

const watching = compiler.watch({

1366

// Wait 300ms before rebuilding

1367

aggregateTimeout: 300,

1368

1369

// Poll every second for changes (useful in containers)

1370

poll: 1000,

1371

1372

// Ignore node_modules and .git

1373

ignored: ["node_modules/**", ".git/**"]

1374

}, (err, stats) => {

1375

if (err) {

1376

console.error(err);

1377

return;

1378

}

1379

1380

console.log(stats.toString({

1381

colors: true,

1382

modules: false,

1383

children: false,

1384

chunks: false,

1385

chunkModules: false

1386

}));

1387

});

1388

1389

// Stop watching

1390

process.on("SIGINT", () => {

1391

watching.close((err) => {

1392

if (err) console.error(err);

1393

console.log("Watching stopped");

1394

});

1395

});

1396

```

1397

1398

### Stats Options

1399

1400

Build statistics and output formatting configuration.

1401

1402

```javascript { .api }

1403

interface StatsOptions {

1404

/** Preset configurations */

1405

preset?:

1406

| "normal"

1407

| "none"

1408

| "minimal"

1409

| "errors-only"

1410

| "errors-warnings"

1411

| "summary"

1412

| "detailed"

1413

| "verbose";

1414

1415

/** All stats options (overrides preset) */

1416

all?: boolean;

1417

1418

/** Show asset information */

1419

assets?: boolean;

1420

1421

/** Sort assets */

1422

assetsSort?: string;

1423

1424

/** Asset space limit */

1425

assetsSpace?: number;

1426

1427

/** Show built date/time */

1428

builtAt?: boolean;

1429

1430

/** Show chunks information */

1431

chunks?: boolean;

1432

1433

/** Show chunk groups */

1434

chunkGroups?: boolean;

1435

1436

/** Show chunk modules */

1437

chunkModules?: boolean;

1438

1439

/** Chunk modules space limit */

1440

chunkModulesSpace?: number;

1441

1442

/** Show chunk origins */

1443

chunkOrigins?: boolean;

1444

1445

/** Sort chunks */

1446

chunksSort?: string;

1447

1448

/** Show colors in output */

1449

colors?: boolean;

1450

1451

/** Context directory for relative paths */

1452

context?: string;

1453

1454

/** Show compilation date */

1455

date?: boolean;

1456

1457

/** Show dependency count */

1458

dependenciesSpace?: number;

1459

1460

/** Show build duration */

1461

timings?: boolean;

1462

1463

/** Show entry points */

1464

entrypoints?: boolean | "auto";

1465

1466

/** Show environment */

1467

env?: boolean;

1468

1469

/** Show error details */

1470

errorDetails?: boolean | "auto";

1471

1472

/** Show error stack traces */

1473

errorStack?: boolean;

1474

1475

/** Show errors */

1476

errors?: boolean;

1477

1478

/** Show errors count */

1479

errorsCount?: boolean;

1480

1481

/** Show webpack hash */

1482

hash?: boolean;

1483

1484

/** Show logging output */

1485

logging?: boolean | LoggingLevel;

1486

1487

/** Show modules information */

1488

modules?: boolean;

1489

1490

/** Sort modules */

1491

modulesSort?: string;

1492

1493

/** Modules space limit */

1494

modulesSpace?: number;

1495

1496

/** Show module trace for errors/warnings */

1497

moduleTrace?: boolean;

1498

1499

/** Show output path */

1500

outputPath?: boolean;

1501

1502

/** Show performance hints */

1503

performance?: boolean;

1504

1505

/** Show preset used */

1506

preset?: string;

1507

1508

/** Show provided exports */

1509

providedExports?: boolean;

1510

1511

/** Show public path */

1512

publicPath?: boolean;

1513

1514

/** Show reasons for module inclusion */

1515

reasons?: boolean;

1516

1517

/** Reasons space limit */

1518

reasonsSpace?: number;

1519

1520

/** Show related assets */

1521

relatedAssets?: boolean;

1522

1523

/** Show runtime modules */

1524

runtimeModules?: boolean;

1525

1526

/** Show source maps */

1527

source?: boolean;

1528

1529

/** Show used exports */

1530

usedExports?: boolean;

1531

1532

/** Show version */

1533

version?: boolean;

1534

1535

/** Show warnings */

1536

warnings?: boolean;

1537

1538

/** Show warnings count */

1539

warningsCount?: boolean;

1540

1541

/** Warnings filter */

1542

warningsFilter?: string | RegExp | ((warning: string) => boolean) | Array<string | RegExp | ((warning: string) => boolean)>;

1543

1544

/** Show children statistics */

1545

children?: boolean | StatsOptions;

1546

}

1547

1548

type LoggingLevel = "none" | "error" | "warn" | "info" | "log" | "verbose";

1549

```

1550

1551

**Usage Examples:**

1552

1553

```javascript

1554

module.exports = {

1555

// Preset-based configuration

1556

stats: "errors-only",

1557

1558

// Detailed custom configuration

1559

stats: {

1560

colors: true,

1561

modules: false,

1562

children: false,

1563

chunks: false,

1564

chunkModules: false,

1565

entrypoints: false,

1566

assets: false,

1567

version: false,

1568

builtAt: false,

1569

timings: true,

1570

performance: true,

1571

errors: true,

1572

warnings: true

1573

},

1574

1575

// Development-friendly stats

1576

stats: {

1577

preset: "minimal",

1578

colors: true,

1579

timings: true,

1580

errors: true,

1581

warnings: true,

1582

errorDetails: true

1583

}

1584

};

1585

1586

// Programmatic stats formatting

1587

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

1588

if (err) {

1589

console.error(err);

1590

return;

1591

}

1592

1593

console.log(stats.toString({

1594

chunks: false,

1595

colors: true,

1596

modules: false

1597

}));

1598

1599

// JSON stats for analysis tools

1600

const statsJson = stats.toJson({

1601

assets: true,

1602

chunks: true,

1603

modules: true,

1604

errors: true,

1605

warnings: true

1606

});

1607

});

1608

```

1609

1610

## Multi-Configuration Support

1611

1612

Webpack supports building multiple configurations simultaneously for different targets or environments.

1613

1614

```javascript { .api }

1615

/** Multiple configuration array */

1616

type MultiConfiguration = Configuration[];

1617

1618

/** Function returning multiple configurations */

1619

type MultiConfigurationFunction = (

1620

env: any,

1621

argv: any

1622

) => MultiConfiguration | Promise<MultiConfiguration>;

1623

```

1624

1625

**Usage Examples:**

1626

1627

```javascript

1628

// Array of configurations

1629

module.exports = [

1630

// Client build

1631

{

1632

name: "client",

1633

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

1634

target: "web",

1635

output: {

1636

filename: "client.js",

1637

path: path.resolve(__dirname, "dist/client")

1638

}

1639

},

1640

1641

// Server build

1642

{

1643

name: "server",

1644

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

1645

target: "node",

1646

output: {

1647

filename: "server.js",

1648

path: path.resolve(__dirname, "dist/server")

1649

}

1650

},

1651

1652

// Web Worker build

1653

{

1654

name: "worker",

1655

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

1656

target: "webworker",

1657

output: {

1658

filename: "worker.js",

1659

path: path.resolve(__dirname, "dist")

1660

}

1661

}

1662

];

1663

1664

// Function-based multi-configuration

1665

module.exports = (env, argv) => {

1666

const isProduction = argv.mode === "production";

1667

1668

return [

1669

{

1670

name: "main",

1671

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

1672

mode: argv.mode,

1673

optimization: {

1674

minimize: isProduction

1675

}

1676

},

1677

1678

// Only build worker in production

1679

...(isProduction ? [{

1680

name: "worker",

1681

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

1682

target: "webworker"

1683

}] : [])

1684

];

1685

};

1686

1687

// Shared configuration with environment-specific overrides

1688

const baseConfig = {

1689

module: {

1690

rules: [

1691

{ test: /\.js$/, use: "babel-loader" }

1692

]

1693

}

1694

};

1695

1696

module.exports = [

1697

{

1698

...baseConfig,

1699

name: "development",

1700

mode: "development",

1701

devtool: "eval-source-map"

1702

},

1703

{

1704

...baseConfig,

1705

name: "production",

1706

mode: "production",

1707

devtool: "source-map"

1708

}

1709

];

1710

```

1711

1712

## Common Configuration Patterns

1713

1714

### Development Configuration

1715

1716

```javascript

1717

module.exports = {

1718

mode: "development",

1719

devtool: "eval-cheap-module-source-map",

1720

1721

entry: {

1722

main: ["webpack-hot-middleware/client", "./src/index.js"]

1723

},

1724

1725

output: {

1726

filename: "[name].js",

1727

path: path.resolve(__dirname, "dist"),

1728

publicPath: "/"

1729

},

1730

1731

module: {

1732

rules: [

1733

{

1734

test: /\.(js|jsx)$/,

1735

exclude: /node_modules/,

1736

use: {

1737

loader: "babel-loader",

1738

options: {

1739

cacheDirectory: true

1740

}

1741

}

1742

}

1743

]

1744

},

1745

1746

plugins: [

1747

new webpack.HotModuleReplacementPlugin(),

1748

new webpack.DefinePlugin({

1749

"process.env.NODE_ENV": JSON.stringify("development")

1750

})

1751

],

1752

1753

optimization: {

1754

splitChunks: {

1755

chunks: "all"

1756

}

1757

},

1758

1759

stats: "minimal",

1760

1761

watchOptions: {

1762

aggregateTimeout: 300,

1763

ignored: /node_modules/

1764

}

1765

};

1766

```

1767

1768

### Production Configuration

1769

1770

```javascript

1771

module.exports = {

1772

mode: "production",

1773

devtool: "source-map",

1774

1775

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

1776

1777

output: {

1778

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

1779

chunkFilename: "[name].[contenthash].chunk.js",

1780

path: path.resolve(__dirname, "dist"),

1781

publicPath: "/assets/",

1782

clean: true

1783

},

1784

1785

module: {

1786

rules: [

1787

{

1788

test: /\.(js|jsx)$/,

1789

exclude: /node_modules/,

1790

use: "babel-loader"

1791

},

1792

{

1793

test: /\.css$/,

1794

use: [MiniCssExtractPlugin.loader, "css-loader"]

1795

}

1796

]

1797

},

1798

1799

plugins: [

1800

new MiniCssExtractPlugin({

1801

filename: "[name].[contenthash].css"

1802

}),

1803

new webpack.DefinePlugin({

1804

"process.env.NODE_ENV": JSON.stringify("production")

1805

})

1806

],

1807

1808

optimization: {

1809

minimize: true,

1810

minimizer: [

1811

new TerserPlugin({

1812

terserOptions: {

1813

compress: {

1814

drop_console: true

1815

}

1816

}

1817

})

1818

],

1819

splitChunks: {

1820

chunks: "all",

1821

cacheGroups: {

1822

vendor: {

1823

test: /[\\/]node_modules[\\/]/,

1824

name: "vendors",

1825

chunks: "all"

1826

}

1827

}

1828

},

1829

runtimeChunk: "single",

1830

moduleIds: "deterministic",

1831

chunkIds: "deterministic"

1832

},

1833

1834

performance: {

1835

maxAssetSize: 250000,

1836

maxEntrypointSize: 250000

1837

}

1838

};

1839

```

1840

1841

### Library Configuration

1842

1843

```javascript

1844

module.exports = {

1845

mode: "production",

1846

1847

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

1848

1849

output: {

1850

filename: "my-library.js",

1851

path: path.resolve(__dirname, "dist"),

1852

library: {

1853

name: "MyLibrary",

1854

type: "umd"

1855

},

1856

globalObject: "this"

1857

},

1858

1859

externals: {

1860

react: {

1861

commonjs: "react",

1862

commonjs2: "react",

1863

amd: "React",

1864

root: "React"

1865

}

1866

},

1867

1868

module: {

1869

rules: [

1870

{

1871

test: /\.js$/,

1872

exclude: /node_modules/,

1873

use: "babel-loader"

1874

}

1875

]

1876

},

1877

1878

optimization: {

1879

minimize: true

1880

}

1881

};

1882

```