CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack

A comprehensive module bundler and build tool for JavaScript applications with advanced optimization and plugin system.

Pending
Overview
Eval results
Files

runtime-system.mddocs/

Runtime System

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.

Capabilities

RuntimeGlobals Constants

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

/**
 * Constants for webpack runtime globals
 * Used to reference webpack's runtime functions in generated code
 */
const RuntimeGlobals = {
  /** Main webpack require function */
  require: "__webpack_require__",
  
  /** Module cache object */
  moduleCache: "__webpack_require__.cache",
  
  /** Module factories object */
  moduleFactories: "__webpack_require__.m",
  
  /** Ensure chunk function */
  ensureChunk: "__webpack_require__.e",
  
  /** Ensure chunk handlers */
  ensureChunkHandlers: "__webpack_require__.f",
  
  /** Ensure chunk includes */
  ensureChunkIncludeEntries: "__webpack_require__.X",
  
  /** Prefetch chunk function */
  prefetchChunk: "__webpack_require__.E",
  
  /** Preload chunk function */
  preloadChunk: "__webpack_require__.G",
  
  /** Has own property shortcut */
  hasOwnProperty: "__webpack_require__.o",
  
  /** Define property getters */
  definePropertyGetters: "__webpack_require__.d",
  
  /** Get default export */
  getDefaultExport: "__webpack_require__.n",
  
  /** Harmony module decorator */
  makeNamespaceObject: "__webpack_require__.r",
  
  /** Create fake namespace object */
  createFakeNamespaceObject: "__webpack_require__.t",
  
  /** Get chunk script filename */
  getChunkScriptFilename: "__webpack_require__.u",
  
  /** Get chunk CSS filename */
  getChunkCssFilename: "__webpack_require__.k",
  
  /** Get chunk update script filename */
  getChunkUpdateScriptFilename: "__webpack_require__.hu",
  
  /** Get chunk update CSS filename */
  getChunkUpdateCssFilename: "__webpack_require__.hk",
  
  /** Startup function */
  startup: "__webpack_require__.x",
  
  /** Startup no default */
  startupNoDefault: "__webpack_require__.xs",
  
  /** Load script function */
  loadScript: "__webpack_require__.l",
  
  /** Create script function */
  createScript: "__webpack_require__.ts",
  
  /** Create script URL */
  createScriptUrl: "__webpack_require__.tu",
  
  /** Get trusted types policy */
  getTrustedTypesPolicy: "__webpack_require__.tt",
  
  /** Relative URL function */
  relativeUrl: "__webpack_require__.relative",
  
  /** Base URI */
  baseURI: "__webpack_require__.b",
  
  /** Global object */
  global: "__webpack_require__.g",
  
  /** Share scope map */
  shareScopeMap: "__webpack_share_scopes__",
  
  /** Share scope */
  shareScope: "webpackChunkName",
  
  /** Initialize sharing */
  initializeSharing: "__webpack_require__.I",
  
  /** Current remote get scope */
  currentRemoteGetScope: "__webpack_require__.R",
  
  /** Get filename function */
  getFilename: "__webpack_require__.p",
  
  /** Script nonce */
  scriptNonce: "__webpack_require__.nc",
  
  /** Uncaught error handler */
  uncaughtErrorHandler: "__webpack_require__.oe",
  
  /** Script source URL */
  scriptSourceUrl: "__webpack_require__.su",
  
  /** AMD define */
  amdDefine: "__webpack_require__.amdD",
  
  /** AMD options */
  amdOptions: "__webpack_require__.amdO",
  
  /** System context */
  system: "__webpack_require__.System",
  
  /** Intersection observer */
  intersectionObserver: "__webpack_require__.jo",
  
  /** Webpack version */
  webpackVersion: "__webpack_require__.rv",
  
  /** Webpack hash */
  webpackHash: "__webpack_require__.h",
  
  /** Export star */
  exportStar: "__webpack_require__.es",
  
  /** Webpack exports */
  webpackExports: "__webpack_exports__",
  
  /** Installation ended */
  onChunksLoaded: "__webpack_require__.O",
  
  /** External install chunk */
  externalInstallChunk: "__webpack_require__.C",
  
  /** Normal entry */
  entryModuleId: "__webpack_require__.s",
  
  /** Module loaded */
  moduleLoaded: "__webpack_require__.nmd",
  
  /** Node module decorator */
  nodeModuleDecorator: "__webpack_require__.nmd",
  
  /** Async module */
  asyncModule: "__webpack_require__.a"
};

Usage Examples:

// Using RuntimeGlobals in a runtime module
class CustomRuntimeModule extends RuntimeModule {
  generate() {
    return Template.asString([
      `${RuntimeGlobals.require}.myCustomFunction = function() {`,
      Template.indent("console.log('Custom runtime function');"),
      "};"
    ]);
  }
}

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

RuntimeModule Base Class

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

class RuntimeModule extends Module {
  /** Runtime module name */
  name: string;
  
  /** Stage when this runtime module should be executed */
  stage: number;
  
  /** Whether this module should be cached */
  cacheable: boolean;
  
  /** Full hash dependency flag */
  fullHash: boolean;
  
  /** Dependent hash flag */
  dependentHash: boolean;
  
  /**
   * Create a runtime module
   * @param name - Name of the runtime module
   * @param stage - Execution stage (default: RuntimeModule.STAGE_NORMAL)
   */
  constructor(name: string, stage?: number);
  
  /**
   * Generate runtime code for this module
   * @returns Generated runtime code as string
   */
  generate(): string | null;
  
  /**
   * Get readable identifier for this runtime module
   * @param requestShortener - Request shortener function
   * @returns Human-readable identifier
   */
  readableIdentifier(requestShortener: RequestShortener): string;
  
  /**
   * Check if runtime module should be in same chunk as another module
   * @param module - Other module to check
   * @returns True if should be in same chunk
   */
  shouldIsolate(): boolean;
  
  /**
   * Attach runtime requirements to this module
   * @param chunk - Target chunk
   * @param set - Set of runtime requirements
   * @param compilation - Current compilation
   * @param chunkGraph - Chunk graph
   * @param runtimeRequirements - Runtime requirements to add
   */
  static getCompilationHooks(compilation: Compilation): RuntimeModuleHooks;
}

// Runtime module execution stages
RuntimeModule.STAGE_STARTUP_ONLY = -1000;
RuntimeModule.STAGE_STARTUP_ENTRYPOINT = -500;
RuntimeModule.STAGE_STARTUP = -100;
RuntimeModule.STAGE_NORMAL = 0;
RuntimeModule.STAGE_BASIC = 5;
RuntimeModule.STAGE_ATTACH = 10;
RuntimeModule.STAGE_TRIGGER = 20;

interface RuntimeModuleHooks {
  /** Called when runtime module is generated */
  generate: SyncWaterfallHook<[string, RuntimeModule]>;
}

Usage Examples:

// Custom runtime module implementation
class LogRuntimeModule extends RuntimeModule {
  constructor() {
    super("LogRuntimeModule", RuntimeModule.STAGE_STARTUP);
  }
  
  generate() {
    return Template.asString([
      "// Runtime logging utility",
      `${RuntimeGlobals.require}.log = function(message) {`,
      Template.indent("console.log('[Runtime]', message);"),
      "};"
    ]);
  }
}

// Using in plugin
class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap("MyPlugin", (compilation) => {
      compilation.hooks.additionalChunkRuntimeRequirements.tap(
        "MyPlugin", 
        (chunk, set) => {
          if (chunk.hasEntryModule()) {
            compilation.addRuntimeModule(chunk, new LogRuntimeModule());
          }
        }
      );
    });
  }
}

RuntimeTemplate for Code Generation

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

class RuntimeTemplate {
  /** Compilation instance */
  compilation: Compilation;
  
  /** Output options */
  outputOptions: OutputNormalized;
  
  /** Request shortener for readable names */
  requestShortener: RequestShortener;
  
  /**
   * Create runtime template
   * @param compilation - Current compilation
   * @param outputOptions - Output configuration
   * @param requestShortener - Request shortener utility
   */
  constructor(
    compilation: Compilation,
    outputOptions: OutputNormalized,
    requestShortener: RequestShortener
  );
  
  /**
   * Generate comment with given information
   * @param options - Comment options
   * @returns Comment string or empty string
   */
  comment(options: {
    request?: string;
    chunkName?: string;
    chunkReason?: string;
    message?: string;
    exportName?: string;
  }): string;
  
  /**
   * Generate require expression for module
   * @param chunkGraph - Chunk graph
   * @param chunk - Target chunk
   * @param module - Module to require
   * @param request - Request string
   * @returns Require expression
   */
  moduleId(options: {
    module: Module;
    chunkGraph: ChunkGraph;
    compilation: Compilation;
    runtimeTemplate: RuntimeTemplate;
  }): string;
  
  /**
   * Generate module namespace object access
   * @param options - Module access options
   * @returns Namespace access expression
   */
  moduleNamespacePromise(options: {
    chunkGraph: ChunkGraph;
    block: AsyncDependenciesBlock | null;
    module: Module;
    request: string;
    strict: boolean;
    message: string;
    weak?: boolean;
    runtimeRequirements: Set<string>;
  }): string;
  
  /**
   * Generate import statement for module
   * @param options - Import options
   * @returns Import expression
   */
  moduleExports(options: {
    module: Module;
    chunkGraph: ChunkGraph;
    request: string;
    weak?: boolean;
    runtimeRequirements: Set<string>;
  }): string;
  
  /**
   * Generate dynamic import for chunk
   * @param options - Import options
   * @returns Promise expression for dynamic import
   */
  importStatement(options: {
    update: boolean;
    module: Module;
    chunkGraph: ChunkGraph;
    request: string;
    originModule: Module | null;
    weak?: boolean;
    runtimeRequirements: Set<string>;
  }): [string, string];
  
  /**
   * Generate expression to get export from module
   * @param options - Export access options
   * @returns Export access expression
   */
  exportFromImport(options: {
    moduleGraph: ModuleGraph;
    module: Module;
    request: string;
    exportName: string | string[] | null;
    originModule: Module;
    asiSafe?: boolean;
    isCall?: boolean;
    callContext?: string | null;
    defaultInterop?: boolean;
    importVar: string;
    initFragments: InitFragment[];
    runtime: RuntimeSpec;
    runtimeRequirements: Set<string>;
  }): string;
  
  /**
   * Generate block promise for async loading
   * @param options - Block options
   * @returns Block promise expression
   */
  blockPromise(options: {
    block: AsyncDependenciesBlock;
    message: string;
    chunkGraph: ChunkGraph;
    runtimeRequirements: Set<string>;
  }): string;
  
  /**
   * Generate expression for async module
   * @param options - Async module options
   * @returns Async module expression
   */
  asyncModuleFactory(options: {
    block: AsyncDependenciesBlock;
    chunkGraph: ChunkGraph;
    runtimeRequirements: Set<string>;
    request?: string;
  }): string;
  
  /**
   * Generate condition to check if chunks are loaded
   * @param chunkIds - Array of chunk IDs to check
   * @param chunkGraph - Chunk graph
   * @param runtimeRequirements - Runtime requirements set
   * @returns Condition expression
   */
  returningFunction(
    returnValue: string, 
    args?: string | string[]
  ): string;
  
  /**
   * Generate basic function wrapper
   * @param args - Function arguments
   * @param body - Function body
   * @returns Function expression
   */
  basicFunction(args: string, body: string | string[]): string;
  
  /**
   * Generate destructuring assignment
   * @param array - Array of variable names
   * @param value - Value to destructure
   * @returns Destructuring expression
   */
  destructureArray(array: string[], value: string): string;
  
  /**
   * Generate destructuring assignment for object
   * @param object - Object property mapping
   * @param value - Value to destructure
   * @returns Destructuring expression
   */
  destructureObject(object: Record<string, string>, value: string): string;
  
  /**
   * Check if identifier is safe to use
   * @param identifier - Identifier to check
   * @returns True if safe
   */
  iife(args: string, body: string): string;
  
  /**
   * Generate forEach loop
   * @param array - Array expression
   * @param iterator - Iterator function
   * @returns ForEach loop expression
   */
  forEach(array: string, iterator: string): string;
}

Chunk Loading Runtime Modules

GetChunkFilenameRuntimeModule

Runtime module that provides chunk filename generation functionality.

class GetChunkFilenameRuntimeModule extends RuntimeModule {
  /** Source type (javascript, css, etc.) */
  sourceType: string;
  
  /** Global variable name */
  globalObject: string;
  
  /** Template for chunk filenames */
  template: string;
  
  /** Whether to use chunks for filename generation */
  useChunks: boolean;
  
  /**
   * Create chunk filename runtime module
   * @param sourceType - Type of source (javascript, css, etc.)
   * @param name - Runtime module name
   * @param globalObject - Global object name
   * @param getFilenameForChunk - Function to get filename for chunk
   * @param useChunks - Whether to use chunks in filename generation
   */
  constructor(
    sourceType: string,
    name: string,
    globalObject: string,
    getFilenameForChunk: (chunk: Chunk) => string,
    useChunks: boolean
  );
  
  /**
   * Generate runtime code for chunk filename function
   * @returns Runtime code string
   */
  generate(): string;
}

LoadScriptRuntimeModule

Runtime module for dynamic script loading functionality.

class LoadScriptRuntimeModule extends RuntimeModule {
  /** Whether to create script URL */
  withCreateScriptUrl: boolean;
  
  /** Whether to use fetch priority */
  withFetchPriority: boolean;
  
  /**
   * Create load script runtime module
   * @param withCreateScriptUrl - Include script URL creation
   * @param withFetchPriority - Include fetch priority support
   */
  constructor(
    withCreateScriptUrl?: boolean, 
    withFetchPriority?: boolean
  );
  
  /**
   * Generate script loading runtime code
   * @returns Runtime code for loading scripts
   */
  generate(): string;
  
  /**
   * Generate script creation code if enabled
   * @param compilation - Current compilation
   * @param crossOriginLoading - Cross-origin loading configuration
   * @param chunkLoadTimeout - Timeout for chunk loading
   * @returns Script creation code
   */
  static generateLoadScript(
    compilation: Compilation,
    crossOriginLoading: string | false,
    chunkLoadTimeout: number
  ): string;
}

Platform-Specific Loading Modules

JsonpChunkLoadingRuntimeModule

JSONP-based chunk loading for web browsers.

class JsonpChunkLoadingRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /**
   * Create JSONP chunk loading runtime module
   * @param runtimeRequirements - Set of required runtime features
   */
  constructor(runtimeRequirements: ReadonlySet<string>);
  
  /**
   * Generate JSONP chunk loading code
   * @returns Runtime code for JSONP chunk loading
   */
  generate(): string;
  
  /**
   * Get chunk loading global variable
   * @param compilation - Current compilation
   * @returns Global variable expression
   */
  static getChunkLoadingGlobal(compilation: Compilation): string;
}

Usage Examples:

// Generated JSONP chunk loading code structure
(self["webpackChunkMyApp"] = self["webpackChunkMyApp"] || []).push([
  ["chunk-name"],
  {
    "module-id": function(module, exports, require) {
      // Module code
    }
  }
]);

// Runtime function for loading chunks
__webpack_require__.e = function(chunkId) {
  return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {
    __webpack_require__.f[key](chunkId, promises);
    return promises;
  }, []));
};

ModuleChunkLoadingRuntimeModule

ESM-based chunk loading for modern JavaScript environments.

class ModuleChunkLoadingRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /** Whether this is for async chunks */
  asyncChunkLoading: boolean;
  
  /**
   * Create ESM chunk loading runtime module
   * @param runtimeRequirements - Required runtime features
   * @param asyncChunkLoading - Enable async chunk loading
   */
  constructor(
    runtimeRequirements: ReadonlySet<string>,
    asyncChunkLoading?: boolean
  );
  
  /**
   * Generate ESM chunk loading code
   * @returns Runtime code for ESM imports
   */
  generate(): string;
}

NodeChunkLoadingRuntimeModule

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

class NodeChunkLoadingRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /**
   * Create Node.js chunk loading runtime module
   * @param runtimeRequirements - Required runtime features
   */
  constructor(runtimeRequirements: ReadonlySet<string>);
  
  /**
   * Generate Node.js chunk loading code
   * @returns Runtime code for Node.js require
   */
  generate(): string;
}

WebWorkerChunkLoadingRuntimeModule

Web Worker-specific chunk loading using importScripts.

class WebWorkerChunkLoadingRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /**
   * Create Web Worker chunk loading runtime module
   * @param runtimeRequirements - Required runtime features
   */
  constructor(runtimeRequirements: ReadonlySet<string>);
  
  /**
   * Generate Web Worker chunk loading code
   * @returns Runtime code using importScripts
   */
  generate(): string;
}

Hot Module Replacement Runtime

HotModuleReplacementRuntimeModule

Runtime support for hot module replacement in development.

class HotModuleReplacementRuntimeModule extends RuntimeModule {
  /**
   * Create HMR runtime module
   */
  constructor();
  
  /**
   * Generate HMR runtime code
   * @returns Runtime code for hot module replacement
   */
  generate(): string;
  
  /**
   * Generate hot update chunk filename function
   * @param compilation - Current compilation
   * @param sourceType - Source type (javascript, css)
   * @returns Hot update filename function code
   */
  static generateHotUpdateChunk(
    compilation: Compilation,
    sourceType: string
  ): string;
}

/**
 * Hot update chunk loading for development
 */
class HotUpdateChunkLoadingRuntimeModule extends RuntimeModule {
  /**
   * Generate hot update loading code
   * @returns Runtime code for loading hot updates
   */
  generate(): string;
}

/**
 * Hot module replacement API exposed to modules
 */
interface HotModuleReplacementAPI {
  /** Accept updates for this module */
  accept(): void;
  accept(dependencies: string[], callback?: Function): void;
  accept(dependency: string, callback?: Function): void;
  
  /** Decline updates for this module */
  decline(): void;
  decline(dependencies: string[]): void;
  decline(dependency: string): void;
  
  /** Dispose callback when module is replaced */
  dispose(callback: (data: any) => void): void;
  addDisposeHandler(callback: (data: any) => void): void;
  
  /** Remove dispose handler */
  removeDisposeHandler(callback: (data: any) => void): void;
  
  /** Check if updates are available */
  check(autoApply?: boolean): Promise<string[] | null>;
  
  /** Apply available updates */
  apply(options?: HotApplyOptions): Promise<string[]>;
  
  /** Get update status */
  status(): "idle" | "check" | "prepare" | "ready" | "dispose" | "apply" | "abort" | "fail";
  
  /** Status change handlers */
  status(callback: (status: string) => void): void;
  addStatusHandler(callback: (status: string) => void): void;
  removeStatusHandler(callback: (status: string) => void): void;
  
  /** Data passed between module versions */
  data: any;
}

interface HotApplyOptions {
  /** Ignore unaccepted modules */
  ignoreUnaccepted?: boolean;
  /** Ignore declined modules */
  ignoreDeclined?: boolean;
  /** Ignore error handler */
  ignoreErrored?: boolean;
  /** Callback for disposed modules */
  onDeclined?: (info: any) => void;
  /** Callback for unaccepted modules */
  onUnaccepted?: (info: any) => void;
  /** Callback for accepted modules */
  onAccepted?: (info: any) => void;
  /** Callback for disposed modules */
  onDisposed?: (info: any) => void;
  /** Callback for errors during apply */
  onErrored?: (info: any) => void;
}

Usage Examples:

// HMR API usage in modules
if (module.hot) {
  // Accept updates for this module
  module.hot.accept('./dependency', () => {
    // Handle dependency update
    console.log('Dependency updated');
  });
  
  // Store data for next version
  module.hot.dispose((data) => {
    data.timestamp = Date.now();
  });
  
  // Check for updates
  if (module.hot.status() === 'idle') {
    module.hot.check().then((updatedModules) => {
      if (updatedModules) {
        return module.hot.apply();
      }
    });
  }
}

Module Federation Runtime

ContainerEntryRuntimeModule

Runtime module for module federation container entry points.

class ContainerEntryRuntimeModule extends RuntimeModule {
  /** Container name */
  name: string;
  
  /** Exposed modules map */
  exposes: Map<string, ExposeOptions>;
  
  /** Shared dependencies */
  shareScope: string;
  
  /**
   * Create container entry runtime module
   * @param name - Container name
   * @param exposes - Map of exposed modules
   * @param shareScope - Shared scope name
   */
  constructor(
    name: string,
    exposes: Map<string, ExposeOptions>,
    shareScope: string
  );
  
  /**
   * Generate container entry code
   * @returns Runtime code for module federation container
   */
  generate(): string;
}

interface ExposeOptions {
  /** Import request for exposed module */
  import: string[];
  /** Name of exposed module */
  name: string;
}

RemoteRuntimeModule

Runtime module for consuming remote module federation containers.

class RemoteRuntimeModule extends RuntimeModule {
  /** Remote container request */
  request: string;
  
  /** External type */
  externalType: string;
  
  /**
   * Create remote runtime module
   * @param request - Remote container request
   * @param externalType - Type of external (var, module, etc.)
   */
  constructor(request: string, externalType: string);
  
  /**
   * Generate remote container loading code
   * @returns Runtime code for loading remote containers
   */
  generate(): string;
}

ShareRuntimeModule

Runtime module for shared dependencies in module federation.

class ShareRuntimeModule extends RuntimeModule {
  /** Share scope name */
  shareScope: string;
  
  /** Shared dependencies configuration */
  provides: Map<string, ProvideOptions>;
  
  /**
   * Create share runtime module
   * @param shareScope - Share scope name
   * @param provides - Map of provided shared modules
   */
  constructor(
    shareScope: string,
    provides: Map<string, ProvideOptions>
  );
  
  /**
   * Generate shared dependencies runtime code
   * @returns Runtime code for sharing modules
   */
  generate(): string;
}

interface ProvideOptions {
  /** Share key */
  shareKey: string;
  /** Share configuration */
  config: ShareConfig;
  /** Eager loading flag */
  eager: boolean;
}

interface ShareConfig {
  /** Required version */
  requiredVersion?: string;
  /** Singleton flag */
  singleton?: boolean;
  /** Strict version flag */
  strictVersion?: boolean;
  /** Package name */
  packageName?: string;
}

WebAssembly Runtime Support

WasmLoadingRuntimeModule

Runtime module for WebAssembly loading support.

class WasmLoadingRuntimeModule extends RuntimeModule {
  /** Whether to generate fetch compile WASM */
  generateFetchCompileWasm: boolean;
  
  /** Whether to generate fetch compile async WASM */
  generateFetchCompileAsyncWasm: boolean;
  
  /**
   * Create WASM loading runtime module
   * @param options - WASM loading options
   */
  constructor(options: {
    generateFetchCompileWasm?: boolean;
    generateFetchCompileAsyncWasm?: boolean;
  });
  
  /**
   * Generate WebAssembly loading runtime code
   * @returns Runtime code for WASM loading
   */
  generate(): string;
}

/**
 * Async WebAssembly runtime module
 */
class AsyncWebAssemblyRuntimeModule extends RuntimeModule {
  /**
   * Generate async WASM runtime code
   * @returns Runtime code for async WebAssembly
   */
  generate(): string;
}

CSS Loading Runtime

CssLoadingRuntimeModule

Runtime module for CSS loading and management.

class CssLoadingRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /** Whether to support HMR for CSS */
  withHmr: boolean;
  
  /**
   * Create CSS loading runtime module
   * @param runtimeRequirements - Required runtime features
   * @param withHmr - Enable hot module replacement for CSS
   */
  constructor(
    runtimeRequirements: ReadonlySet<string>,
    withHmr?: boolean
  );
  
  /**
   * Generate CSS loading runtime code
   * @returns Runtime code for loading CSS
   */
  generate(): string;
}

/**
 * Mini CSS extract runtime module
 */
class MiniCssExtractRuntimeModule extends RuntimeModule {
  /** Whether to support HMR */
  withHmr: boolean;
  
  /**
   * Generate mini CSS extract runtime code
   * @returns Runtime code for extracted CSS
   */
  generate(): string;
}

Runtime Optimization

StartupChunkDependenciesRuntimeModule

Manages startup chunk dependencies and loading order.

class StartupChunkDependenciesRuntimeModule extends RuntimeModule {
  /** Startup chunks that need to be loaded */
  startupChunks: Set<Chunk>;
  
  /**
   * Create startup dependencies runtime module
   * @param startupChunks - Set of startup chunks
   */
  constructor(startupChunks: Set<Chunk>);
  
  /**
   * Generate startup dependencies code
   * @returns Runtime code for startup chunk loading
   */
  generate(): string;
}

OnChunksLoadedRuntimeModule

Runtime module for tracking when chunks are loaded.

class OnChunksLoadedRuntimeModule extends RuntimeModule {
  /**
   * Generate chunks loaded tracking code
   * @returns Runtime code for chunk loading callbacks
   */
  generate(): string;
}

ChunkPrefetchPreloadRuntimeModule

Runtime support for chunk prefetching and preloading.

class ChunkPrefetchPreloadRuntimeModule extends RuntimeModule {
  /** Set of runtime requirements */
  runtimeRequirements: ReadonlySet<string>;
  
  /**
   * Create prefetch/preload runtime module
   * @param runtimeRequirements - Required runtime features
   */
  constructor(runtimeRequirements: ReadonlySet<string>);
  
  /**
   * Generate prefetch/preload runtime code
   * @returns Runtime code for chunk prefetching
   */
  generate(): string;
}

Runtime Stages and Execution Order

/**
 * Runtime execution stages define the order of runtime module execution
 */
enum RuntimeStage {
  /** Startup-only modules (executed once) */
  STARTUP_ONLY = -1000,
  
  /** Entry point startup modules */
  STARTUP_ENTRYPOINT = -500,
  
  /** General startup modules */
  STARTUP = -100,
  
  /** Normal runtime modules */
  NORMAL = 0,
  
  /** Basic runtime functionality */
  BASIC = 5,
  
  /** Attachment phase modules */
  ATTACH = 10,
  
  /** Trigger phase modules */  
  TRIGGER = 20
}

/**
 * Runtime module execution context
 */
interface RuntimeModuleExecutionContext {
  /** Current chunk being processed */
  chunk: Chunk;
  
  /** Chunk graph instance */
  chunkGraph: ChunkGraph;
  
  /** Current compilation */
  compilation: Compilation;
  
  /** Runtime requirements for this chunk */
  runtimeRequirements: Set<string>;
  
  /** Runtime template for code generation */
  runtimeTemplate: RuntimeTemplate;
}

Common Types and Interfaces

interface RuntimeSpec {
  /** Runtime identifier */
  runtime?: string | string[];
}

interface ChunkLoadingType {
  /** Type of chunk loading (jsonp, import, require, etc.) */
  type: "jsonp" | "import" | "require" | "async-node" | "import-scripts";
}

interface WasmLoadingType {
  /** Type of WASM loading */
  type: "fetch" | "async-node" | "universal";
}

interface RuntimeRequirement {
  /** Runtime global constant */
  global: string;
  /** Dependencies on other runtime requirements */
  dependencies?: Set<string>;
  /** Stage for execution */
  stage?: number;
}

interface ChunkLoadingContext {
  /** Target chunk */
  chunk: Chunk;
  /** Chunk loading type */
  type: ChunkLoadingType;
  /** Runtime requirements */
  runtimeRequirements: Set<string>;
  /** Chunk graph */
  chunkGraph: ChunkGraph;
  /** Compilation instance */
  compilation: Compilation;
}

/**
 * Template utilities for runtime code generation
 */
class Template {
  /**
   * Convert array of strings to properly indented code
   * @param lines - Array of code lines
   * @returns Formatted code string
   */
  static asString(lines: (string | string[])[]): string;
  
  /**
   * Indent code lines
   * @param str - Code to indent
   * @param prefix - Indentation prefix (default: tab)
   * @returns Indented code
   */
  static indent(str: string | string[], prefix?: string): string | string[];
  
  /**
   * Create comma-separated list
   * @param items - Array of items
   * @returns Comma-separated string
   */
  static toIdentifier(str: string): string;
  
  /**
   * Convert string to valid JavaScript identifier
   * @param str - Input string
   * @returns Valid identifier
   */
  static toComment(str: string): string;
  
  /**
   * Convert string to JavaScript comment
   * @param str - Comment content
   * @returns Formatted comment
   */
  static toNormalComment(str: string): string;
}

Usage Patterns

Creating Custom Runtime Modules

// Custom runtime module for logging
class DebugRuntimeModule extends RuntimeModule {
  constructor() {
    super("DebugRuntimeModule", RuntimeModule.STAGE_STARTUP);
    this.fullHash = true;
  }
  
  generate() {
    const { compilation, chunk, chunkGraph } = this;
    const { runtimeTemplate } = compilation;
    
    return Template.asString([
      "// Debug runtime module",
      `${RuntimeGlobals.require}.debug = {`,
      Template.indent([
        `version: ${JSON.stringify(compilation.hash)},`,
        `chunk: ${JSON.stringify(chunk.name)},`,
        `modules: ${chunkGraph.getNumberOfChunkModules(chunk)},`,
        "log: function(msg) { console.log('[DEBUG]', msg); }"
      ]),
      "};"
    ]);
  }
}

Platform-Specific Loading

// Custom chunk loading for Electron
class ElectronChunkLoadingRuntimeModule extends RuntimeModule {
  constructor(runtimeRequirements) {
    super("ElectronChunkLoadingRuntimeModule");
    this.runtimeRequirements = runtimeRequirements;
  }
  
  generate() {
    const { compilation } = this;
    const { outputOptions } = compilation;
    const chunkLoadingGlobal = JSON.stringify(outputOptions.chunkLoadingGlobal);
    
    return Template.asString([
      "// Electron chunk loading",
      `${RuntimeGlobals.require}.e = function(chunkId) {`,
      Template.indent([
        "return new Promise(function(resolve, reject) {",
        Template.indent([
          `var filename = ${RuntimeGlobals.require}.u(chunkId);`,
          `var script = require('path').resolve(__dirname, filename);`,
          "try {",
          Template.indent([
            "delete require.cache[script];",
            "var chunk = require(script);",
            `if (!chunk || !chunk[${chunkLoadingGlobal}]) {`,
            Template.indent("reject(new Error('Chunk loading failed'));"),
            "} else {",
            Template.indent("resolve();"),
            "}"
          ]),
          "} catch (err) {",
          Template.indent("reject(err);"),
          "}"
        ]),
        "});"
      ]),
      "};"
    ]);
  }
}

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.

Install with Tessl CLI

npx tessl i tessl/npm-webpack

docs

configuration.md

core-compilation.md

development-tools.md

index.md

module-system.md

optimization.md

plugins.md

runtime-system.md

utilities.md

tile.json