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

runtime-system.mddocs/

0

# Runtime System

1

2

Webpack's runtime system is the foundation that enables module loading, chunk management, and dynamic imports in the bundled application. It provides platform-specific implementations for different environments (web, Node.js, ESM, WebWorkers) and manages the runtime code generation that makes webpack bundles work across different execution contexts.

3

4

## Capabilities

5

6

### RuntimeGlobals Constants

7

8

Constants that define webpack's runtime global functions and variables used throughout the generated code.

9

10

```javascript { .api }

11

/**

12

* Constants for webpack runtime globals

13

* Used to reference webpack's runtime functions in generated code

14

*/

15

const RuntimeGlobals = {

16

/** Main webpack require function */

17

require: "__webpack_require__",

18

19

/** Module cache object */

20

moduleCache: "__webpack_require__.cache",

21

22

/** Module factories object */

23

moduleFactories: "__webpack_require__.m",

24

25

/** Ensure chunk function */

26

ensureChunk: "__webpack_require__.e",

27

28

/** Ensure chunk handlers */

29

ensureChunkHandlers: "__webpack_require__.f",

30

31

/** Ensure chunk includes */

32

ensureChunkIncludeEntries: "__webpack_require__.X",

33

34

/** Prefetch chunk function */

35

prefetchChunk: "__webpack_require__.E",

36

37

/** Preload chunk function */

38

preloadChunk: "__webpack_require__.G",

39

40

/** Has own property shortcut */

41

hasOwnProperty: "__webpack_require__.o",

42

43

/** Define property getters */

44

definePropertyGetters: "__webpack_require__.d",

45

46

/** Get default export */

47

getDefaultExport: "__webpack_require__.n",

48

49

/** Harmony module decorator */

50

makeNamespaceObject: "__webpack_require__.r",

51

52

/** Create fake namespace object */

53

createFakeNamespaceObject: "__webpack_require__.t",

54

55

/** Get chunk script filename */

56

getChunkScriptFilename: "__webpack_require__.u",

57

58

/** Get chunk CSS filename */

59

getChunkCssFilename: "__webpack_require__.k",

60

61

/** Get chunk update script filename */

62

getChunkUpdateScriptFilename: "__webpack_require__.hu",

63

64

/** Get chunk update CSS filename */

65

getChunkUpdateCssFilename: "__webpack_require__.hk",

66

67

/** Startup function */

68

startup: "__webpack_require__.x",

69

70

/** Startup no default */

71

startupNoDefault: "__webpack_require__.xs",

72

73

/** Load script function */

74

loadScript: "__webpack_require__.l",

75

76

/** Create script function */

77

createScript: "__webpack_require__.ts",

78

79

/** Create script URL */

80

createScriptUrl: "__webpack_require__.tu",

81

82

/** Get trusted types policy */

83

getTrustedTypesPolicy: "__webpack_require__.tt",

84

85

/** Relative URL function */

86

relativeUrl: "__webpack_require__.relative",

87

88

/** Base URI */

89

baseURI: "__webpack_require__.b",

90

91

/** Global object */

92

global: "__webpack_require__.g",

93

94

/** Share scope map */

95

shareScopeMap: "__webpack_share_scopes__",

96

97

/** Share scope */

98

shareScope: "webpackChunkName",

99

100

/** Initialize sharing */

101

initializeSharing: "__webpack_require__.I",

102

103

/** Current remote get scope */

104

currentRemoteGetScope: "__webpack_require__.R",

105

106

/** Get filename function */

107

getFilename: "__webpack_require__.p",

108

109

/** Script nonce */

110

scriptNonce: "__webpack_require__.nc",

111

112

/** Uncaught error handler */

113

uncaughtErrorHandler: "__webpack_require__.oe",

114

115

/** Script source URL */

116

scriptSourceUrl: "__webpack_require__.su",

117

118

/** AMD define */

119

amdDefine: "__webpack_require__.amdD",

120

121

/** AMD options */

122

amdOptions: "__webpack_require__.amdO",

123

124

/** System context */

125

system: "__webpack_require__.System",

126

127

/** Intersection observer */

128

intersectionObserver: "__webpack_require__.jo",

129

130

/** Webpack version */

131

webpackVersion: "__webpack_require__.rv",

132

133

/** Webpack hash */

134

webpackHash: "__webpack_require__.h",

135

136

/** Export star */

137

exportStar: "__webpack_require__.es",

138

139

/** Webpack exports */

140

webpackExports: "__webpack_exports__",

141

142

/** Installation ended */

143

onChunksLoaded: "__webpack_require__.O",

144

145

/** External install chunk */

146

externalInstallChunk: "__webpack_require__.C",

147

148

/** Normal entry */

149

entryModuleId: "__webpack_require__.s",

150

151

/** Module loaded */

152

moduleLoaded: "__webpack_require__.nmd",

153

154

/** Node module decorator */

155

nodeModuleDecorator: "__webpack_require__.nmd",

156

157

/** Async module */

158

asyncModule: "__webpack_require__.a"

159

};

160

```

161

162

**Usage Examples:**

163

164

```javascript

165

// Using RuntimeGlobals in a runtime module

166

class CustomRuntimeModule extends RuntimeModule {

167

generate() {

168

return Template.asString([

169

`${RuntimeGlobals.require}.myCustomFunction = function() {`,

170

Template.indent("console.log('Custom runtime function');"),

171

"};"

172

]);

173

}

174

}

175

176

// Referencing in template code

177

const code = `${RuntimeGlobals.require}(${JSON.stringify(moduleId)})`;

178

```

179

180

### RuntimeModule Base Class

181

182

Base class for all webpack runtime modules that generate runtime code for specific functionality.

183

184

```javascript { .api }

185

class RuntimeModule extends Module {

186

/** Runtime module name */

187

name: string;

188

189

/** Stage when this runtime module should be executed */

190

stage: number;

191

192

/** Whether this module should be cached */

193

cacheable: boolean;

194

195

/** Full hash dependency flag */

196

fullHash: boolean;

197

198

/** Dependent hash flag */

199

dependentHash: boolean;

200

201

/**

202

* Create a runtime module

203

* @param name - Name of the runtime module

204

* @param stage - Execution stage (default: RuntimeModule.STAGE_NORMAL)

205

*/

206

constructor(name: string, stage?: number);

207

208

/**

209

* Generate runtime code for this module

210

* @returns Generated runtime code as string

211

*/

212

generate(): string | null;

213

214

/**

215

* Get readable identifier for this runtime module

216

* @param requestShortener - Request shortener function

217

* @returns Human-readable identifier

218

*/

219

readableIdentifier(requestShortener: RequestShortener): string;

220

221

/**

222

* Check if runtime module should be in same chunk as another module

223

* @param module - Other module to check

224

* @returns True if should be in same chunk

225

*/

226

shouldIsolate(): boolean;

227

228

/**

229

* Attach runtime requirements to this module

230

* @param chunk - Target chunk

231

* @param set - Set of runtime requirements

232

* @param compilation - Current compilation

233

* @param chunkGraph - Chunk graph

234

* @param runtimeRequirements - Runtime requirements to add

235

*/

236

static getCompilationHooks(compilation: Compilation): RuntimeModuleHooks;

237

}

238

239

// Runtime module execution stages

240

RuntimeModule.STAGE_STARTUP_ONLY = -1000;

241

RuntimeModule.STAGE_STARTUP_ENTRYPOINT = -500;

242

RuntimeModule.STAGE_STARTUP = -100;

243

RuntimeModule.STAGE_NORMAL = 0;

244

RuntimeModule.STAGE_BASIC = 5;

245

RuntimeModule.STAGE_ATTACH = 10;

246

RuntimeModule.STAGE_TRIGGER = 20;

247

248

interface RuntimeModuleHooks {

249

/** Called when runtime module is generated */

250

generate: SyncWaterfallHook<[string, RuntimeModule]>;

251

}

252

```

253

254

**Usage Examples:**

255

256

```javascript

257

// Custom runtime module implementation

258

class LogRuntimeModule extends RuntimeModule {

259

constructor() {

260

super("LogRuntimeModule", RuntimeModule.STAGE_STARTUP);

261

}

262

263

generate() {

264

return Template.asString([

265

"// Runtime logging utility",

266

`${RuntimeGlobals.require}.log = function(message) {`,

267

Template.indent("console.log('[Runtime]', message);"),

268

"};"

269

]);

270

}

271

}

272

273

// Using in plugin

274

class MyPlugin {

275

apply(compiler) {

276

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

277

compilation.hooks.additionalChunkRuntimeRequirements.tap(

278

"MyPlugin",

279

(chunk, set) => {

280

if (chunk.hasEntryModule()) {

281

compilation.addRuntimeModule(chunk, new LogRuntimeModule());

282

}

283

}

284

);

285

});

286

}

287

}

288

```

289

290

### RuntimeTemplate for Code Generation

291

292

Utility class for generating runtime code with proper formatting and optimization.

293

294

```javascript { .api }

295

class RuntimeTemplate {

296

/** Compilation instance */

297

compilation: Compilation;

298

299

/** Output options */

300

outputOptions: OutputNormalized;

301

302

/** Request shortener for readable names */

303

requestShortener: RequestShortener;

304

305

/**

306

* Create runtime template

307

* @param compilation - Current compilation

308

* @param outputOptions - Output configuration

309

* @param requestShortener - Request shortener utility

310

*/

311

constructor(

312

compilation: Compilation,

313

outputOptions: OutputNormalized,

314

requestShortener: RequestShortener

315

);

316

317

/**

318

* Generate comment with given information

319

* @param options - Comment options

320

* @returns Comment string or empty string

321

*/

322

comment(options: {

323

request?: string;

324

chunkName?: string;

325

chunkReason?: string;

326

message?: string;

327

exportName?: string;

328

}): string;

329

330

/**

331

* Generate require expression for module

332

* @param chunkGraph - Chunk graph

333

* @param chunk - Target chunk

334

* @param module - Module to require

335

* @param request - Request string

336

* @returns Require expression

337

*/

338

moduleId(options: {

339

module: Module;

340

chunkGraph: ChunkGraph;

341

compilation: Compilation;

342

runtimeTemplate: RuntimeTemplate;

343

}): string;

344

345

/**

346

* Generate module namespace object access

347

* @param options - Module access options

348

* @returns Namespace access expression

349

*/

350

moduleNamespacePromise(options: {

351

chunkGraph: ChunkGraph;

352

block: AsyncDependenciesBlock | null;

353

module: Module;

354

request: string;

355

strict: boolean;

356

message: string;

357

weak?: boolean;

358

runtimeRequirements: Set<string>;

359

}): string;

360

361

/**

362

* Generate import statement for module

363

* @param options - Import options

364

* @returns Import expression

365

*/

366

moduleExports(options: {

367

module: Module;

368

chunkGraph: ChunkGraph;

369

request: string;

370

weak?: boolean;

371

runtimeRequirements: Set<string>;

372

}): string;

373

374

/**

375

* Generate dynamic import for chunk

376

* @param options - Import options

377

* @returns Promise expression for dynamic import

378

*/

379

importStatement(options: {

380

update: boolean;

381

module: Module;

382

chunkGraph: ChunkGraph;

383

request: string;

384

originModule: Module | null;

385

weak?: boolean;

386

runtimeRequirements: Set<string>;

387

}): [string, string];

388

389

/**

390

* Generate expression to get export from module

391

* @param options - Export access options

392

* @returns Export access expression

393

*/

394

exportFromImport(options: {

395

moduleGraph: ModuleGraph;

396

module: Module;

397

request: string;

398

exportName: string | string[] | null;

399

originModule: Module;

400

asiSafe?: boolean;

401

isCall?: boolean;

402

callContext?: string | null;

403

defaultInterop?: boolean;

404

importVar: string;

405

initFragments: InitFragment[];

406

runtime: RuntimeSpec;

407

runtimeRequirements: Set<string>;

408

}): string;

409

410

/**

411

* Generate block promise for async loading

412

* @param options - Block options

413

* @returns Block promise expression

414

*/

415

blockPromise(options: {

416

block: AsyncDependenciesBlock;

417

message: string;

418

chunkGraph: ChunkGraph;

419

runtimeRequirements: Set<string>;

420

}): string;

421

422

/**

423

* Generate expression for async module

424

* @param options - Async module options

425

* @returns Async module expression

426

*/

427

asyncModuleFactory(options: {

428

block: AsyncDependenciesBlock;

429

chunkGraph: ChunkGraph;

430

runtimeRequirements: Set<string>;

431

request?: string;

432

}): string;

433

434

/**

435

* Generate condition to check if chunks are loaded

436

* @param chunkIds - Array of chunk IDs to check

437

* @param chunkGraph - Chunk graph

438

* @param runtimeRequirements - Runtime requirements set

439

* @returns Condition expression

440

*/

441

returningFunction(

442

returnValue: string,

443

args?: string | string[]

444

): string;

445

446

/**

447

* Generate basic function wrapper

448

* @param args - Function arguments

449

* @param body - Function body

450

* @returns Function expression

451

*/

452

basicFunction(args: string, body: string | string[]): string;

453

454

/**

455

* Generate destructuring assignment

456

* @param array - Array of variable names

457

* @param value - Value to destructure

458

* @returns Destructuring expression

459

*/

460

destructureArray(array: string[], value: string): string;

461

462

/**

463

* Generate destructuring assignment for object

464

* @param object - Object property mapping

465

* @param value - Value to destructure

466

* @returns Destructuring expression

467

*/

468

destructureObject(object: Record<string, string>, value: string): string;

469

470

/**

471

* Check if identifier is safe to use

472

* @param identifier - Identifier to check

473

* @returns True if safe

474

*/

475

iife(args: string, body: string): string;

476

477

/**

478

* Generate forEach loop

479

* @param array - Array expression

480

* @param iterator - Iterator function

481

* @returns ForEach loop expression

482

*/

483

forEach(array: string, iterator: string): string;

484

}

485

```

486

487

### Chunk Loading Runtime Modules

488

489

#### GetChunkFilenameRuntimeModule

490

491

Runtime module that provides chunk filename generation functionality.

492

493

```javascript { .api }

494

class GetChunkFilenameRuntimeModule extends RuntimeModule {

495

/** Source type (javascript, css, etc.) */

496

sourceType: string;

497

498

/** Global variable name */

499

globalObject: string;

500

501

/** Template for chunk filenames */

502

template: string;

503

504

/** Whether to use chunks for filename generation */

505

useChunks: boolean;

506

507

/**

508

* Create chunk filename runtime module

509

* @param sourceType - Type of source (javascript, css, etc.)

510

* @param name - Runtime module name

511

* @param globalObject - Global object name

512

* @param getFilenameForChunk - Function to get filename for chunk

513

* @param useChunks - Whether to use chunks in filename generation

514

*/

515

constructor(

516

sourceType: string,

517

name: string,

518

globalObject: string,

519

getFilenameForChunk: (chunk: Chunk) => string,

520

useChunks: boolean

521

);

522

523

/**

524

* Generate runtime code for chunk filename function

525

* @returns Runtime code string

526

*/

527

generate(): string;

528

}

529

```

530

531

#### LoadScriptRuntimeModule

532

533

Runtime module for dynamic script loading functionality.

534

535

```javascript { .api }

536

class LoadScriptRuntimeModule extends RuntimeModule {

537

/** Whether to create script URL */

538

withCreateScriptUrl: boolean;

539

540

/** Whether to use fetch priority */

541

withFetchPriority: boolean;

542

543

/**

544

* Create load script runtime module

545

* @param withCreateScriptUrl - Include script URL creation

546

* @param withFetchPriority - Include fetch priority support

547

*/

548

constructor(

549

withCreateScriptUrl?: boolean,

550

withFetchPriority?: boolean

551

);

552

553

/**

554

* Generate script loading runtime code

555

* @returns Runtime code for loading scripts

556

*/

557

generate(): string;

558

559

/**

560

* Generate script creation code if enabled

561

* @param compilation - Current compilation

562

* @param crossOriginLoading - Cross-origin loading configuration

563

* @param chunkLoadTimeout - Timeout for chunk loading

564

* @returns Script creation code

565

*/

566

static generateLoadScript(

567

compilation: Compilation,

568

crossOriginLoading: string | false,

569

chunkLoadTimeout: number

570

): string;

571

}

572

```

573

574

### Platform-Specific Loading Modules

575

576

#### JsonpChunkLoadingRuntimeModule

577

578

JSONP-based chunk loading for web browsers.

579

580

```javascript { .api }

581

class JsonpChunkLoadingRuntimeModule extends RuntimeModule {

582

/** Set of runtime requirements */

583

runtimeRequirements: ReadonlySet<string>;

584

585

/**

586

* Create JSONP chunk loading runtime module

587

* @param runtimeRequirements - Set of required runtime features

588

*/

589

constructor(runtimeRequirements: ReadonlySet<string>);

590

591

/**

592

* Generate JSONP chunk loading code

593

* @returns Runtime code for JSONP chunk loading

594

*/

595

generate(): string;

596

597

/**

598

* Get chunk loading global variable

599

* @param compilation - Current compilation

600

* @returns Global variable expression

601

*/

602

static getChunkLoadingGlobal(compilation: Compilation): string;

603

}

604

```

605

606

**Usage Examples:**

607

608

```javascript

609

// Generated JSONP chunk loading code structure

610

(self["webpackChunkMyApp"] = self["webpackChunkMyApp"] || []).push([

611

["chunk-name"],

612

{

613

"module-id": function(module, exports, require) {

614

// Module code

615

}

616

}

617

]);

618

619

// Runtime function for loading chunks

620

__webpack_require__.e = function(chunkId) {

621

return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {

622

__webpack_require__.f[key](chunkId, promises);

623

return promises;

624

}, []));

625

};

626

```

627

628

#### ModuleChunkLoadingRuntimeModule

629

630

ESM-based chunk loading for modern JavaScript environments.

631

632

```javascript { .api }

633

class ModuleChunkLoadingRuntimeModule extends RuntimeModule {

634

/** Set of runtime requirements */

635

runtimeRequirements: ReadonlySet<string>;

636

637

/** Whether this is for async chunks */

638

asyncChunkLoading: boolean;

639

640

/**

641

* Create ESM chunk loading runtime module

642

* @param runtimeRequirements - Required runtime features

643

* @param asyncChunkLoading - Enable async chunk loading

644

*/

645

constructor(

646

runtimeRequirements: ReadonlySet<string>,

647

asyncChunkLoading?: boolean

648

);

649

650

/**

651

* Generate ESM chunk loading code

652

* @returns Runtime code for ESM imports

653

*/

654

generate(): string;

655

}

656

```

657

658

#### NodeChunkLoadingRuntimeModule

659

660

Node.js-based chunk loading using require().

661

662

```javascript { .api }

663

class NodeChunkLoadingRuntimeModule extends RuntimeModule {

664

/** Set of runtime requirements */

665

runtimeRequirements: ReadonlySet<string>;

666

667

/**

668

* Create Node.js chunk loading runtime module

669

* @param runtimeRequirements - Required runtime features

670

*/

671

constructor(runtimeRequirements: ReadonlySet<string>);

672

673

/**

674

* Generate Node.js chunk loading code

675

* @returns Runtime code for Node.js require

676

*/

677

generate(): string;

678

}

679

```

680

681

#### WebWorkerChunkLoadingRuntimeModule

682

683

Web Worker-specific chunk loading using importScripts.

684

685

```javascript { .api }

686

class WebWorkerChunkLoadingRuntimeModule extends RuntimeModule {

687

/** Set of runtime requirements */

688

runtimeRequirements: ReadonlySet<string>;

689

690

/**

691

* Create Web Worker chunk loading runtime module

692

* @param runtimeRequirements - Required runtime features

693

*/

694

constructor(runtimeRequirements: ReadonlySet<string>);

695

696

/**

697

* Generate Web Worker chunk loading code

698

* @returns Runtime code using importScripts

699

*/

700

generate(): string;

701

}

702

```

703

704

### Hot Module Replacement Runtime

705

706

#### HotModuleReplacementRuntimeModule

707

708

Runtime support for hot module replacement in development.

709

710

```javascript { .api }

711

class HotModuleReplacementRuntimeModule extends RuntimeModule {

712

/**

713

* Create HMR runtime module

714

*/

715

constructor();

716

717

/**

718

* Generate HMR runtime code

719

* @returns Runtime code for hot module replacement

720

*/

721

generate(): string;

722

723

/**

724

* Generate hot update chunk filename function

725

* @param compilation - Current compilation

726

* @param sourceType - Source type (javascript, css)

727

* @returns Hot update filename function code

728

*/

729

static generateHotUpdateChunk(

730

compilation: Compilation,

731

sourceType: string

732

): string;

733

}

734

735

/**

736

* Hot update chunk loading for development

737

*/

738

class HotUpdateChunkLoadingRuntimeModule extends RuntimeModule {

739

/**

740

* Generate hot update loading code

741

* @returns Runtime code for loading hot updates

742

*/

743

generate(): string;

744

}

745

746

/**

747

* Hot module replacement API exposed to modules

748

*/

749

interface HotModuleReplacementAPI {

750

/** Accept updates for this module */

751

accept(): void;

752

accept(dependencies: string[], callback?: Function): void;

753

accept(dependency: string, callback?: Function): void;

754

755

/** Decline updates for this module */

756

decline(): void;

757

decline(dependencies: string[]): void;

758

decline(dependency: string): void;

759

760

/** Dispose callback when module is replaced */

761

dispose(callback: (data: any) => void): void;

762

addDisposeHandler(callback: (data: any) => void): void;

763

764

/** Remove dispose handler */

765

removeDisposeHandler(callback: (data: any) => void): void;

766

767

/** Check if updates are available */

768

check(autoApply?: boolean): Promise<string[] | null>;

769

770

/** Apply available updates */

771

apply(options?: HotApplyOptions): Promise<string[]>;

772

773

/** Get update status */

774

status(): "idle" | "check" | "prepare" | "ready" | "dispose" | "apply" | "abort" | "fail";

775

776

/** Status change handlers */

777

status(callback: (status: string) => void): void;

778

addStatusHandler(callback: (status: string) => void): void;

779

removeStatusHandler(callback: (status: string) => void): void;

780

781

/** Data passed between module versions */

782

data: any;

783

}

784

785

interface HotApplyOptions {

786

/** Ignore unaccepted modules */

787

ignoreUnaccepted?: boolean;

788

/** Ignore declined modules */

789

ignoreDeclined?: boolean;

790

/** Ignore error handler */

791

ignoreErrored?: boolean;

792

/** Callback for disposed modules */

793

onDeclined?: (info: any) => void;

794

/** Callback for unaccepted modules */

795

onUnaccepted?: (info: any) => void;

796

/** Callback for accepted modules */

797

onAccepted?: (info: any) => void;

798

/** Callback for disposed modules */

799

onDisposed?: (info: any) => void;

800

/** Callback for errors during apply */

801

onErrored?: (info: any) => void;

802

}

803

```

804

805

**Usage Examples:**

806

807

```javascript

808

// HMR API usage in modules

809

if (module.hot) {

810

// Accept updates for this module

811

module.hot.accept('./dependency', () => {

812

// Handle dependency update

813

console.log('Dependency updated');

814

});

815

816

// Store data for next version

817

module.hot.dispose((data) => {

818

data.timestamp = Date.now();

819

});

820

821

// Check for updates

822

if (module.hot.status() === 'idle') {

823

module.hot.check().then((updatedModules) => {

824

if (updatedModules) {

825

return module.hot.apply();

826

}

827

});

828

}

829

}

830

```

831

832

### Module Federation Runtime

833

834

#### ContainerEntryRuntimeModule

835

836

Runtime module for module federation container entry points.

837

838

```javascript { .api }

839

class ContainerEntryRuntimeModule extends RuntimeModule {

840

/** Container name */

841

name: string;

842

843

/** Exposed modules map */

844

exposes: Map<string, ExposeOptions>;

845

846

/** Shared dependencies */

847

shareScope: string;

848

849

/**

850

* Create container entry runtime module

851

* @param name - Container name

852

* @param exposes - Map of exposed modules

853

* @param shareScope - Shared scope name

854

*/

855

constructor(

856

name: string,

857

exposes: Map<string, ExposeOptions>,

858

shareScope: string

859

);

860

861

/**

862

* Generate container entry code

863

* @returns Runtime code for module federation container

864

*/

865

generate(): string;

866

}

867

868

interface ExposeOptions {

869

/** Import request for exposed module */

870

import: string[];

871

/** Name of exposed module */

872

name: string;

873

}

874

```

875

876

#### RemoteRuntimeModule

877

878

Runtime module for consuming remote module federation containers.

879

880

```javascript { .api }

881

class RemoteRuntimeModule extends RuntimeModule {

882

/** Remote container request */

883

request: string;

884

885

/** External type */

886

externalType: string;

887

888

/**

889

* Create remote runtime module

890

* @param request - Remote container request

891

* @param externalType - Type of external (var, module, etc.)

892

*/

893

constructor(request: string, externalType: string);

894

895

/**

896

* Generate remote container loading code

897

* @returns Runtime code for loading remote containers

898

*/

899

generate(): string;

900

}

901

```

902

903

#### ShareRuntimeModule

904

905

Runtime module for shared dependencies in module federation.

906

907

```javascript { .api }

908

class ShareRuntimeModule extends RuntimeModule {

909

/** Share scope name */

910

shareScope: string;

911

912

/** Shared dependencies configuration */

913

provides: Map<string, ProvideOptions>;

914

915

/**

916

* Create share runtime module

917

* @param shareScope - Share scope name

918

* @param provides - Map of provided shared modules

919

*/

920

constructor(

921

shareScope: string,

922

provides: Map<string, ProvideOptions>

923

);

924

925

/**

926

* Generate shared dependencies runtime code

927

* @returns Runtime code for sharing modules

928

*/

929

generate(): string;

930

}

931

932

interface ProvideOptions {

933

/** Share key */

934

shareKey: string;

935

/** Share configuration */

936

config: ShareConfig;

937

/** Eager loading flag */

938

eager: boolean;

939

}

940

941

interface ShareConfig {

942

/** Required version */

943

requiredVersion?: string;

944

/** Singleton flag */

945

singleton?: boolean;

946

/** Strict version flag */

947

strictVersion?: boolean;

948

/** Package name */

949

packageName?: string;

950

}

951

```

952

953

### WebAssembly Runtime Support

954

955

#### WasmLoadingRuntimeModule

956

957

Runtime module for WebAssembly loading support.

958

959

```javascript { .api }

960

class WasmLoadingRuntimeModule extends RuntimeModule {

961

/** Whether to generate fetch compile WASM */

962

generateFetchCompileWasm: boolean;

963

964

/** Whether to generate fetch compile async WASM */

965

generateFetchCompileAsyncWasm: boolean;

966

967

/**

968

* Create WASM loading runtime module

969

* @param options - WASM loading options

970

*/

971

constructor(options: {

972

generateFetchCompileWasm?: boolean;

973

generateFetchCompileAsyncWasm?: boolean;

974

});

975

976

/**

977

* Generate WebAssembly loading runtime code

978

* @returns Runtime code for WASM loading

979

*/

980

generate(): string;

981

}

982

983

/**

984

* Async WebAssembly runtime module

985

*/

986

class AsyncWebAssemblyRuntimeModule extends RuntimeModule {

987

/**

988

* Generate async WASM runtime code

989

* @returns Runtime code for async WebAssembly

990

*/

991

generate(): string;

992

}

993

```

994

995

### CSS Loading Runtime

996

997

#### CssLoadingRuntimeModule

998

999

Runtime module for CSS loading and management.

1000

1001

```javascript { .api }

1002

class CssLoadingRuntimeModule extends RuntimeModule {

1003

/** Set of runtime requirements */

1004

runtimeRequirements: ReadonlySet<string>;

1005

1006

/** Whether to support HMR for CSS */

1007

withHmr: boolean;

1008

1009

/**

1010

* Create CSS loading runtime module

1011

* @param runtimeRequirements - Required runtime features

1012

* @param withHmr - Enable hot module replacement for CSS

1013

*/

1014

constructor(

1015

runtimeRequirements: ReadonlySet<string>,

1016

withHmr?: boolean

1017

);

1018

1019

/**

1020

* Generate CSS loading runtime code

1021

* @returns Runtime code for loading CSS

1022

*/

1023

generate(): string;

1024

}

1025

1026

/**

1027

* Mini CSS extract runtime module

1028

*/

1029

class MiniCssExtractRuntimeModule extends RuntimeModule {

1030

/** Whether to support HMR */

1031

withHmr: boolean;

1032

1033

/**

1034

* Generate mini CSS extract runtime code

1035

* @returns Runtime code for extracted CSS

1036

*/

1037

generate(): string;

1038

}

1039

```

1040

1041

### Runtime Optimization

1042

1043

#### StartupChunkDependenciesRuntimeModule

1044

1045

Manages startup chunk dependencies and loading order.

1046

1047

```javascript { .api }

1048

class StartupChunkDependenciesRuntimeModule extends RuntimeModule {

1049

/** Startup chunks that need to be loaded */

1050

startupChunks: Set<Chunk>;

1051

1052

/**

1053

* Create startup dependencies runtime module

1054

* @param startupChunks - Set of startup chunks

1055

*/

1056

constructor(startupChunks: Set<Chunk>);

1057

1058

/**

1059

* Generate startup dependencies code

1060

* @returns Runtime code for startup chunk loading

1061

*/

1062

generate(): string;

1063

}

1064

```

1065

1066

#### OnChunksLoadedRuntimeModule

1067

1068

Runtime module for tracking when chunks are loaded.

1069

1070

```javascript { .api }

1071

class OnChunksLoadedRuntimeModule extends RuntimeModule {

1072

/**

1073

* Generate chunks loaded tracking code

1074

* @returns Runtime code for chunk loading callbacks

1075

*/

1076

generate(): string;

1077

}

1078

```

1079

1080

#### ChunkPrefetchPreloadRuntimeModule

1081

1082

Runtime support for chunk prefetching and preloading.

1083

1084

```javascript { .api }

1085

class ChunkPrefetchPreloadRuntimeModule extends RuntimeModule {

1086

/** Set of runtime requirements */

1087

runtimeRequirements: ReadonlySet<string>;

1088

1089

/**

1090

* Create prefetch/preload runtime module

1091

* @param runtimeRequirements - Required runtime features

1092

*/

1093

constructor(runtimeRequirements: ReadonlySet<string>);

1094

1095

/**

1096

* Generate prefetch/preload runtime code

1097

* @returns Runtime code for chunk prefetching

1098

*/

1099

generate(): string;

1100

}

1101

```

1102

1103

## Runtime Stages and Execution Order

1104

1105

```javascript { .api }

1106

/**

1107

* Runtime execution stages define the order of runtime module execution

1108

*/

1109

enum RuntimeStage {

1110

/** Startup-only modules (executed once) */

1111

STARTUP_ONLY = -1000,

1112

1113

/** Entry point startup modules */

1114

STARTUP_ENTRYPOINT = -500,

1115

1116

/** General startup modules */

1117

STARTUP = -100,

1118

1119

/** Normal runtime modules */

1120

NORMAL = 0,

1121

1122

/** Basic runtime functionality */

1123

BASIC = 5,

1124

1125

/** Attachment phase modules */

1126

ATTACH = 10,

1127

1128

/** Trigger phase modules */

1129

TRIGGER = 20

1130

}

1131

1132

/**

1133

* Runtime module execution context

1134

*/

1135

interface RuntimeModuleExecutionContext {

1136

/** Current chunk being processed */

1137

chunk: Chunk;

1138

1139

/** Chunk graph instance */

1140

chunkGraph: ChunkGraph;

1141

1142

/** Current compilation */

1143

compilation: Compilation;

1144

1145

/** Runtime requirements for this chunk */

1146

runtimeRequirements: Set<string>;

1147

1148

/** Runtime template for code generation */

1149

runtimeTemplate: RuntimeTemplate;

1150

}

1151

```

1152

1153

## Common Types and Interfaces

1154

1155

```javascript { .api }

1156

interface RuntimeSpec {

1157

/** Runtime identifier */

1158

runtime?: string | string[];

1159

}

1160

1161

interface ChunkLoadingType {

1162

/** Type of chunk loading (jsonp, import, require, etc.) */

1163

type: "jsonp" | "import" | "require" | "async-node" | "import-scripts";

1164

}

1165

1166

interface WasmLoadingType {

1167

/** Type of WASM loading */

1168

type: "fetch" | "async-node" | "universal";

1169

}

1170

1171

interface RuntimeRequirement {

1172

/** Runtime global constant */

1173

global: string;

1174

/** Dependencies on other runtime requirements */

1175

dependencies?: Set<string>;

1176

/** Stage for execution */

1177

stage?: number;

1178

}

1179

1180

interface ChunkLoadingContext {

1181

/** Target chunk */

1182

chunk: Chunk;

1183

/** Chunk loading type */

1184

type: ChunkLoadingType;

1185

/** Runtime requirements */

1186

runtimeRequirements: Set<string>;

1187

/** Chunk graph */

1188

chunkGraph: ChunkGraph;

1189

/** Compilation instance */

1190

compilation: Compilation;

1191

}

1192

1193

/**

1194

* Template utilities for runtime code generation

1195

*/

1196

class Template {

1197

/**

1198

* Convert array of strings to properly indented code

1199

* @param lines - Array of code lines

1200

* @returns Formatted code string

1201

*/

1202

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

1203

1204

/**

1205

* Indent code lines

1206

* @param str - Code to indent

1207

* @param prefix - Indentation prefix (default: tab)

1208

* @returns Indented code

1209

*/

1210

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

1211

1212

/**

1213

* Create comma-separated list

1214

* @param items - Array of items

1215

* @returns Comma-separated string

1216

*/

1217

static toIdentifier(str: string): string;

1218

1219

/**

1220

* Convert string to valid JavaScript identifier

1221

* @param str - Input string

1222

* @returns Valid identifier

1223

*/

1224

static toComment(str: string): string;

1225

1226

/**

1227

* Convert string to JavaScript comment

1228

* @param str - Comment content

1229

* @returns Formatted comment

1230

*/

1231

static toNormalComment(str: string): string;

1232

}

1233

```

1234

1235

## Usage Patterns

1236

1237

### Creating Custom Runtime Modules

1238

1239

```javascript

1240

// Custom runtime module for logging

1241

class DebugRuntimeModule extends RuntimeModule {

1242

constructor() {

1243

super("DebugRuntimeModule", RuntimeModule.STAGE_STARTUP);

1244

this.fullHash = true;

1245

}

1246

1247

generate() {

1248

const { compilation, chunk, chunkGraph } = this;

1249

const { runtimeTemplate } = compilation;

1250

1251

return Template.asString([

1252

"// Debug runtime module",

1253

`${RuntimeGlobals.require}.debug = {`,

1254

Template.indent([

1255

`version: ${JSON.stringify(compilation.hash)},`,

1256

`chunk: ${JSON.stringify(chunk.name)},`,

1257

`modules: ${chunkGraph.getNumberOfChunkModules(chunk)},`,

1258

"log: function(msg) { console.log('[DEBUG]', msg); }"

1259

]),

1260

"};"

1261

]);

1262

}

1263

}

1264

```

1265

1266

### Platform-Specific Loading

1267

1268

```javascript

1269

// Custom chunk loading for Electron

1270

class ElectronChunkLoadingRuntimeModule extends RuntimeModule {

1271

constructor(runtimeRequirements) {

1272

super("ElectronChunkLoadingRuntimeModule");

1273

this.runtimeRequirements = runtimeRequirements;

1274

}

1275

1276

generate() {

1277

const { compilation } = this;

1278

const { outputOptions } = compilation;

1279

const chunkLoadingGlobal = JSON.stringify(outputOptions.chunkLoadingGlobal);

1280

1281

return Template.asString([

1282

"// Electron chunk loading",

1283

`${RuntimeGlobals.require}.e = function(chunkId) {`,

1284

Template.indent([

1285

"return new Promise(function(resolve, reject) {",

1286

Template.indent([

1287

`var filename = ${RuntimeGlobals.require}.u(chunkId);`,

1288

`var script = require('path').resolve(__dirname, filename);`,

1289

"try {",

1290

Template.indent([

1291

"delete require.cache[script];",

1292

"var chunk = require(script);",

1293

`if (!chunk || !chunk[${chunkLoadingGlobal}]) {`,

1294

Template.indent("reject(new Error('Chunk loading failed'));"),

1295

"} else {",

1296

Template.indent("resolve();"),

1297

"}"

1298

]),

1299

"} catch (err) {",

1300

Template.indent("reject(err);"),

1301

"}"

1302

]),

1303

"});"

1304

]),

1305

"};"

1306

]);

1307

}

1308

}

1309

```

1310

1311

The webpack runtime system provides a comprehensive and extensible foundation for module loading across different platforms and environments, enabling sophisticated features like code splitting, hot module replacement, and module federation while maintaining optimal performance and compatibility.