A comprehensive module bundler and build tool for JavaScript applications with advanced optimization and plugin system.
—
The core compilation system is the heart of webpack, orchestrating the entire build process through the Compiler and Compilation classes. This system manages the build lifecycle, hooks, and coordination between all webpack components.
The primary webpack function that creates and optionally runs compiler instances.
/**
* Main webpack compilation function
* @param options - Webpack configuration object or array of configurations
* @param callback - Optional callback for handling compilation results
* @returns Compiler or MultiCompiler instance, or null if callback fails immediately
*/
function webpack(
options: Configuration | MultiConfiguration,
callback?: (err: Error | null, stats?: Stats | MultiStats) => void
): Compiler | MultiCompiler | null;Usage Examples:
const webpack = require("webpack");
// Callback-style usage
webpack(config, (err, stats) => {
if (err || stats.hasErrors()) {
console.error(err || stats.toString());
return;
}
console.log("Build completed successfully!");
});
// Get compiler instance without running
const compiler = webpack(config);The main webpack compiler that orchestrates the build process and provides a hooks-based plugin system.
class Compiler {
/** Webpack configuration options */
options: WebpackOptionsNormalized;
/** Input file system */
inputFileSystem: InputFileSystem;
/** Output file system */
outputFileSystem: OutputFileSystem;
/** Hooks for plugin integration */
hooks: CompilerHooks;
/** Current compilation context */
context: string;
/**
* Run a single build
* @param callback - Callback with error and stats
*/
run(callback: (err: Error | null, stats?: Stats) => void): void;
/**
* Start watching for file changes
* @param watchOptions - Watch configuration
* @param handler - Handler for each compilation
* @returns Watching instance
*/
watch(
watchOptions: WatchOptions,
handler: (err: Error | null, stats?: Stats) => void
): Watching;
/**
* Close the compiler and release resources
* @param callback - Completion callback
*/
close(callback: (err?: Error) => void): void;
/**
* Get webpack cache instance
* @param name - Cache name
* @returns Cache facade
*/
getCache(name: string): CacheFacade;
/**
* Get logger instance
* @param name - Logger name
* @returns Logger instance
*/
getLogger(name: string): WebpackLogger;
/**
* Create child compiler with modified options
* @param compilation - Parent compilation
* @param compilerName - Name for child compiler
* @param compilerIndex - Index for child compiler
* @returns Child compiler instance
*/
createChildCompiler(
compilation: Compilation,
compilerName: string,
compilerIndex?: number
): Compiler;
}
interface CompilerHooks {
/** Before the environment is prepared */
environment: SyncHook<[]>;
/** After the environment is prepared */
afterEnvironment: SyncHook<[]>;
/** Before plugins are initialized */
initialize: SyncHook<[]>;
/** Before running starts */
beforeRun: AsyncSeriesHook<[Compiler]>;
/** When running starts */
run: AsyncSeriesHook<[Compiler]>;
/** Before watching starts */
watchRun: AsyncSeriesHook<[Compiler]>;
/** Before compilation starts */
beforeCompile: AsyncSeriesHook<[CompilationParams]>;
/** When compilation starts */
compile: SyncHook<[CompilationParams]>;
/** This compilation instance */
thisCompilation: SyncHook<[Compilation, CompilationParams]>;
/** Any compilation instance */
compilation: SyncHook<[Compilation, CompilationParams]>;
/** After compilation completes */
afterCompile: AsyncSeriesHook<[Compilation]>;
/** Before emitting assets */
emit: AsyncSeriesHook<[Compilation]>;
/** After emitting assets */
afterEmit: AsyncSeriesHook<[Compilation]>;
/** When build completes */
done: AsyncSeriesHook<[Stats]>;
/** Build completed with errors */
failed: SyncHook<[Error]>;
/** Compilation invalidated */
invalid: SyncHook<[string | null, number]>;
/** Watch stopped */
watchClose: SyncHook<[]>;
}Usage Examples:
const webpack = require("webpack");
const config = require("./webpack.config.js");
const compiler = webpack(config);
// Add plugin via hooks
compiler.hooks.done.tap("MyPlugin", (stats) => {
console.log("Build completed!");
});
// Run single build
compiler.run((err, stats) => {
if (err) {
console.error(err);
return;
}
console.log(stats.toString({
colors: true,
modules: false,
chunks: false
}));
compiler.close((closeErr) => {
if (closeErr) console.error(closeErr);
});
});Manages multiple webpack compiler instances for parallel or sequential builds.
class MultiCompiler {
/** Array of child compilers */
compilers: Compiler[];
/** Dependency relationships between compilers */
dependencies: WeakMap<Compiler, string[]>;
/** Hooks for multi-compiler events */
hooks: MultiCompilerHooks;
/**
* Constructor for MultiCompiler
* @param compilers - Array of compiler instances
* @param options - Multi-compiler options
*/
constructor(compilers: Compiler[], options?: MultiCompilerOptions);
/**
* Run all compilers
* @param callback - Callback with error and multi-stats
*/
run(callback: (err: Error | null, stats?: MultiStats) => void): void;
/**
* Watch all compilers
* @param watchOptions - Watch options for each compiler
* @param handler - Handler for compilation results
* @returns MultiWatching instance
*/
watch(
watchOptions: WatchOptions | WatchOptions[],
handler: (err: Error | null, stats?: MultiStats) => void
): MultiWatching;
/**
* Close all compilers
* @param callback - Completion callback
*/
close(callback: (err?: Error) => void): void;
/**
* Set dependencies between compilers
* @param compiler - Dependent compiler
* @param dependencies - Array of dependency names
*/
setDependencies(compiler: Compiler, dependencies: string[]): void;
/**
* Validate dependencies for circular references
*/
validateDependencies(): void;
/**
* Create normal module factory
* @returns Normal module factory instance
*/
createNormalModuleFactory(): NormalModuleFactory;
/**
* Create context module factory
* @returns Context module factory instance
*/
createContextModuleFactory(): ContextModuleFactory;
/**
* Create new compilation parameters
* @returns Compilation parameters
*/
newCompilationParams(): CompilationParams;
/**
* Create new compilation instance
* @param params - Compilation parameters
* @returns New compilation
*/
createCompilation(params?: CompilationParams): Compilation;
/**
* Create and initialize new compilation
* @param params - Compilation parameters
* @returns Initialized compilation
*/
newCompilation(params: CompilationParams): Compilation;
/**
* Emit assets to output file system
* @param compilation - Compilation with assets
* @param callback - Completion callback
*/
emitAssets(compilation: Compilation, callback: (err?: Error) => void): void;
/**
* Emit records file
* @param callback - Completion callback
*/
emitRecords(callback: (err?: Error) => void): void;
/**
* Read records file
* @param callback - Completion callback
*/
readRecords(callback: (err?: Error) => void): void;
/**
* Run compilation as child process
* @param compilation - Parent compilation
* @param compilerName - Child compiler name
* @param compilerIndex - Child compiler index
* @param outputOptions - Output options for child
* @param plugins - Plugins for child compiler
* @param callback - Completion callback
*/
runAsChild(
compilation: Compilation,
compilerName: string,
compilerIndex: number,
outputOptions: OutputNormalized,
plugins: WebpackPluginInstance[],
callback: (err?: Error, entries?: Chunk[], compilation?: Compilation) => void
): void;
/**
* Check if this is a child compiler
* @returns True if child compiler
*/
isChild(): boolean;
/**
* Purge input file system cache
*/
purgeInputFileSystem(): void;
}
interface MultiCompilerHooks {
/** Before any compiler runs */
done: SyncHook<[MultiStats]>;
/** Invalid event from any compiler */
invalid: MultiHook<SyncHook<[string | null, number]>>;
}
interface MultiCompilerOptions {
/** Parallelism limit for running compilers */
parallelism?: number;
}Represents a single build process containing modules, chunks, and assets.
class Compilation {
/** Parent compiler instance */
compiler: Compiler;
/** Compilation hooks for plugin integration */
hooks: CompilationHooks;
/** All modules in this compilation */
modules: Set<Module>;
/** All chunks generated */
chunks: Set<Chunk>;
/** Generated assets */
assets: Record<string, Asset>;
/** Additional asset information */
assetsInfo: Map<string, AssetInfo>;
/** Compilation errors */
errors: WebpackError[];
/** Compilation warnings */
warnings: WebpackError[];
/** Module graph for dependency tracking */
moduleGraph: ModuleGraph;
/** Chunk graph for chunk relationships */
chunkGraph: ChunkGraph;
/** Code generation results */
codeGenerationResults: CodeGenerationResults;
/**
* Add entry point to compilation
* @param context - Entry context
* @param dependency - Entry dependency
* @param options - Entry options
* @param callback - Completion callback
*/
addEntry(
context: string,
dependency: Dependency,
options: EntryOptions | string,
callback: (err?: Error | null, module?: Module) => void
): void;
/**
* Rebuild a specific module
* @param modules - Modules to rebuild
* @param callback - Completion callback
*/
rebuildModule(
modules: Module[],
callback: (err?: Error | null, module?: Module) => void
): void;
/**
* Create hash for compilation
* @returns Hash string
*/
createHash(): string;
/**
* Emit asset to output
* @param filename - Output filename
* @param source - Asset source
* @param assetInfo - Asset metadata
*/
emitAsset(filename: string, source: Source, assetInfo?: AssetInfo): void;
/**
* Update existing asset
* @param filename - Asset filename
* @param newSource - New source
* @param assetInfoUpdateFn - Function to update asset info
*/
updateAsset(
filename: string,
newSource: Source | ((source: Source) => Source),
assetInfoUpdateFn?: (assetInfo: AssetInfo) => AssetInfo
): void;
/**
* Delete asset from compilation
* @param filename - Asset filename
*/
deleteAsset(filename: string): void;
/**
* Get asset source
* @param filename - Asset filename
* @returns Asset source or undefined
*/
getAsset(filename: string): Asset | undefined;
/**
* Get logger for this compilation
* @param name - Logger name
* @returns Logger instance
*/
getLogger(name: string): WebpackLogger;
}
interface Asset {
/** Asset source */
source: Source;
/** Asset information */
info: AssetInfo;
}
interface AssetInfo {
/** Whether asset is development only */
development?: boolean;
/** Whether asset is hot update only */
hotModuleReplacement?: boolean;
/** Source filename if different */
sourceFilename?: string;
/** Asset size in bytes */
size?: number;
/** Whether asset is immutable */
immutable?: boolean;
/** Whether asset is minimized */
minimized?: boolean;
/** Related assets */
related?: Record<string, string | string[]>;
/** Chunk hash if asset is chunk-specific */
chunkhash?: string | string[];
/** Content hash */
contenthash?: string | string[];
/** Full hash */
fullhash?: string;
}Statistics and information about compilation results.
class Stats {
/** Compilation instance */
compilation: Compilation;
/**
* Constructor for Stats
* @param compilation - Compilation instance
*/
constructor(compilation: Compilation);
/**
* Check if compilation has errors
* @returns True if errors exist
*/
hasErrors(): boolean;
/**
* Check if compilation has warnings
* @returns True if warnings exist
*/
hasWarnings(): boolean;
/**
* Convert stats to string
* @param options - Formatting options
* @returns Formatted string
*/
toString(options?: StatsOptions): string;
/**
* Convert stats to JSON
* @param options - JSON options
* @returns Stats as JSON object
*/
toJson(options?: StatsOptions): StatsCompilation;
}
class MultiStats {
/** Array of child stats */
stats: Stats[];
/**
* Constructor for MultiStats
* @param stats - Array of stats instances
*/
constructor(stats: Stats[]);
/**
* Check if any compilation has errors
* @returns True if any errors exist
*/
hasErrors(): boolean;
/**
* Check if any compilation has warnings
* @returns True if any warnings exist
*/
hasWarnings(): boolean;
/**
* Convert multi-stats to string
* @param options - Formatting options
* @returns Formatted string
*/
toString(options?: MultiStatsOptions): string;
/**
* Convert multi-stats to JSON
* @param options - JSON options
* @returns Multi-stats as JSON object
*/
toJson(options?: MultiStatsOptions): { children: StatsCompilation[] };
}File watching capabilities for development workflows.
class Watching {
/** Associated compiler */
compiler: Compiler;
/** Watching options */
options: WatchOptions;
/** File system watcher */
watcher: any;
/**
* Close watching and cleanup
* @param callback - Completion callback
*/
close(callback?: () => void): void;
/**
* Invalidate current compilation
* @param filename - Optional filename that changed
*/
invalidate(filename?: string): void;
/**
* Suspend watching temporarily
*/
suspend(): void;
/**
* Resume watching after suspension
*/
resume(): void;
}
interface WatchOptions {
/** Delay before rebuilding after change */
aggregateTimeout?: number;
/** Enable polling for file changes */
poll?: boolean | number;
/** Files/directories to ignore */
ignored?: string | RegExp | string[] | ((path: string) => boolean);
/** Follow symbolic links */
followSymlinks?: boolean;
/** Use stdin to stop watching */
stdin?: boolean;
}
class MultiWatching {
/** Array of individual watching instances */
watchings: Watching[];
/** Multi-compiler instance */
compiler: MultiCompiler;
/**
* Close all watching instances
* @param callback - Completion callback
*/
close(callback?: () => void): void;
/**
* Invalidate all watching instances
*/
invalidate(): void;
/**
* Suspend all watching instances
*/
suspend(): void;
/**
* Resume all watching instances
*/
resume(): void;
}interface WebpackOptionsNormalized {
context: string;
entry: EntryNormalized;
mode: "development" | "production" | "none";
output: OutputNormalized;
module: ModuleOptionsNormalized;
resolve: ResolveOptionsNormalized;
plugins: WebpackPluginInstance[];
// ... additional normalized options
}
interface CompilationParams {
normalModuleFactory: NormalModuleFactory;
contextModuleFactory: ContextModuleFactory;
}
interface EntryOptions {
name?: string;
runtime?: string | false;
dependOn?: string | string[];
publicPath?: string;
chunkLoading?: ChunkLoadingType;
asyncChunks?: boolean;
wasmLoading?: WasmLoadingType;
library?: LibraryOptions;
}Install with Tessl CLI
npx tessl i tessl/npm-webpack