A comprehensive module bundler and build tool for JavaScript applications with advanced optimization and plugin system.
—
Webpack's plugin system provides over 60 built-in plugins that extend webpack's core functionality through a powerful hooks-based architecture. Plugins can modify the compilation process, optimize bundles, manage assets, provide development tools, and integrate with various platforms and environments.
Essential plugins that provide fundamental webpack features including global constants, module provision, environment integration, and module replacement.
/**
* Replaces variables with compile-time constants using string replacement
* @param definitions - Object mapping variable names to values
*/
class DefinePlugin {
constructor(definitions: Record<string, any>);
}
/**
* Automatically loads modules when they are used as free variables
* @param definitions - Object mapping variable names to module names/paths
*/
class ProvidePlugin {
constructor(definitions: Record<string, string | string[]>);
}
/**
* Maps environment variables to DefinePlugin definitions
* @param keys - Array of environment variable names or object with defaults
*/
class EnvironmentPlugin {
constructor(keys: string[] | Record<string, any>);
}
/**
* Prevents bundling of certain modules based on request patterns
* @param options - Ignore configuration with resource and context matchers
*/
class IgnorePlugin {
constructor(options: {
resourceRegExp?: RegExp;
contextRegExp?: RegExp;
checkResource?: (resource: string, context: string) => boolean;
});
}
/**
* Replaces the default resource resolution for context modules
* @param resourceRegExp - Pattern to match context requests
* @param newContentResource - New directory or callback for replacement
* @param newContentRecursive - Whether to include subdirectories
* @param newContentRegExp - Pattern to filter files in new context
*/
class ContextReplacementPlugin {
constructor(
resourceRegExp: RegExp,
newContentResource?: string | ((resource: string) => string),
newContentRecursive?: boolean,
newContentRegExp?: RegExp
);
}
/**
* Excludes modules from being included in context module requests
* @param negativeMatcher - Pattern to match modules for exclusion
*/
class ContextExclusionPlugin {
constructor(negativeMatcher: RegExp);
}
/**
* Replaces modules during the normal module factory resolution process
* @param resourceRegExp - Pattern to match module requests
* @param newResource - Replacement module path or callback
*/
class NormalModuleReplacementPlugin {
constructor(
resourceRegExp: RegExp,
newResource: string | ((resource: any) => string)
);
}Usage Examples:
const webpack = require("webpack");
module.exports = {
plugins: [
// Define compile-time constants
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production'),
'API_BASE_URL': JSON.stringify('https://api.example.com'),
'VERSION': JSON.stringify(require('./package.json').version)
}),
// Automatically provide modules
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
process: 'process/browser'
}),
// Map environment variables
new webpack.EnvironmentPlugin({
NODE_ENV: 'development',
DEBUG: false,
API_URL: 'http://localhost:3000'
}),
// Ignore moment.js locales
new webpack.IgnorePlugin({
resourceRegExp: /^\.\/locale$/,
contextRegExp: /moment$/
})
]
};Development-focused plugins that enhance the development experience with hot reloading, progress reporting, source maps, and debugging capabilities.
/**
* Enables Hot Module Replacement for faster development cycles
* @param options - HMR configuration options
*/
class HotModuleReplacementPlugin {
constructor(options?: {
multiStep?: boolean;
fullBuildTimeout?: number;
requestTimeout?: number;
});
}
/**
* Generates source maps with fine-grained control over format and output
* @param options - Source map generation options
*/
class SourceMapDevToolPlugin {
constructor(options?: {
filename?: string | false;
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
moduleFilenameTemplate?: string | ((info: any) => string);
fallbackModuleFilenameTemplate?: string | ((info: any) => string);
append?: string | false;
module?: boolean;
columns?: boolean;
lineToLine?: boolean | { test?: RegExp | Array<RegExp> };
noSources?: boolean;
publicPath?: string;
fileContext?: string;
sourceRoot?: string;
});
}
/**
* Fast source maps using eval() for development builds
* @param options - Eval source map options
*/
class EvalSourceMapDevToolPlugin {
constructor(options?: {
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
moduleFilenameTemplate?: string | ((info: any) => string);
module?: boolean;
columns?: boolean;
lineToLine?: boolean | { test?: RegExp | Array<RegExp> };
});
}
/**
* Wraps modules in eval() statements for better debugging
* @param options - Eval dev tool options
*/
class EvalDevToolModulePlugin {
constructor(options?: {
moduleFilenameTemplate?: string | ((info: any) => string);
sourceUrlComment?: string;
});
}
/**
* Reports compilation progress during builds
* @param options - Progress reporting configuration
*/
class ProgressPlugin {
constructor(options?: {
activeModules?: boolean;
entries?: boolean;
handler?: (percentage: number, message: string, ...args: string[]) => void;
modules?: boolean;
modulesCount?: number;
profile?: boolean;
dependencies?: boolean;
dependenciesCount?: number;
percentBy?: 'entries' | 'modules' | 'dependencies' | null;
});
}Usage Examples:
const webpack = require("webpack");
module.exports = {
mode: 'development',
devtool: false, // Disable default source maps
plugins: [
// Enable HMR
new webpack.HotModuleReplacementPlugin(),
// Custom source map configuration
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
include: /\.js$/,
exclude: /vendor/,
moduleFilenameTemplate: 'webpack://[namespace]/[resource-path]',
columns: false
}),
// Progress reporting
new webpack.ProgressPlugin({
activeModules: true,
handler: (percentage, message, ...args) => {
console.log(`${Math.round(percentage * 100)}%`, message, ...args);
}
})
]
};Advanced optimization plugins that handle code splitting, chunk optimization, module concatenation, and production-ready optimizations.
/**
* Automatically splits chunks based on optimization rules
* @param options - Chunk splitting configuration
*/
class SplitChunksPlugin {
constructor(options?: {
chunks?: 'all' | 'async' | 'initial' | ((chunk: any) => boolean);
minSize?: number | { [key: string]: number };
minRemainingSize?: number | { [key: string]: number };
minChunks?: number;
maxAsyncRequests?: number;
maxInitialRequests?: number;
enforceSizeThreshold?: number | { [key: string]: number };
cacheGroups?: {
[key: string]: {
test?: RegExp | string | ((module: any) => boolean);
name?: string | false | ((module: any) => string);
chunks?: 'all' | 'async' | 'initial' | ((chunk: any) => boolean);
minSize?: number;
minChunks?: number;
maxAsyncRequests?: number;
maxInitialRequests?: number;
priority?: number;
reuseExistingChunk?: boolean;
enforce?: boolean;
};
};
fallbackCacheGroup?: {
minSize?: number;
maxAsyncRequests?: number;
maxInitialRequests?: number;
};
hidePathInfo?: boolean;
});
}
/**
* Extracts webpack runtime code into a separate chunk
* @param options - Runtime chunk configuration
*/
class RuntimeChunkPlugin {
constructor(options?: {
name?: string | ((entrypoint: any) => string) | { name: string | ((entrypoint: any) => string) };
});
}
/**
* Concatenates modules in the same scope to reduce bundle size (scope hoisting)
*/
class ModuleConcatenationPlugin {
constructor();
}
/**
* Merges chunks aggressively to reduce the number of HTTP requests
* @param options - Merging configuration
*/
class AggressiveMergingPlugin {
constructor(options?: {
minSizeReduce?: number;
moveToParents?: boolean;
});
}
/**
* Limits the maximum number of chunks to control resource loading
* @param options - Chunk count limits
*/
class LimitChunkCountPlugin {
constructor(options: {
maxChunks: number;
chunkOverhead?: number;
entryChunkMultiplicator?: number;
});
}
/**
* Ensures chunks meet minimum size requirements
* @param options - Minimum size configuration
*/
class MinChunkSizePlugin {
constructor(options: {
minChunkSize: number;
});
}
/**
* Generates content-based hashes for long-term caching
* @param options - Hash generation options
*/
class RealContentHashPlugin {
constructor(options?: {
hashFunction?: string;
hashDigest?: string;
});
}Usage Examples:
const webpack = require("webpack");
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
priority: 10
},
common: {
minChunks: 2,
chunks: 'all',
name: 'common',
priority: 5,
reuseExistingChunk: true
}
}
},
runtimeChunk: {
name: 'runtime'
}
},
plugins: [
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 5
}),
new webpack.optimize.RealContentHashPlugin()
]
};Plugins for managing build assets including cleaning output directories and adding file banners.
/**
* Cleans the output directory before each build
* @param options - Cleaning configuration
*/
class CleanPlugin {
constructor(options?: {
dry?: boolean;
keep?: string | RegExp | ((filename: string) => boolean);
cleanOnceBeforeBuildPatterns?: string[];
cleanAfterEveryBuildPatterns?: string[];
dangerouslyAllowCleanPatternsOutsideProject?: boolean;
});
}
/**
* Adds banner comments to the top of generated files
* @param options - Banner configuration
*/
class BannerPlugin {
constructor(options: string | {
banner: string | ((data: any) => string);
raw?: boolean;
entryOnly?: boolean;
test?: string | RegExp | Array<string | RegExp>;
include?: string | RegExp | Array<string | RegExp>;
exclude?: string | RegExp | Array<string | RegExp>;
footer?: boolean;
stage?: number;
});
}Usage Examples:
const webpack = require("webpack");
module.exports = {
plugins: [
// Clean output directory
new webpack.CleanPlugin({
cleanAfterEveryBuildPatterns: ['**/*', '!important.js']
}),
// Add copyright banner
new webpack.BannerPlugin({
banner: '/*! Copyright 2023 MyCompany */\n',
raw: true,
test: /\.js$/
})
]
};Plugins that control how webpack generates IDs for modules and chunks, affecting caching and deterministic builds.
/**
* Generates deterministic chunk IDs based on chunk content
* @param options - Deterministic ID options
*/
class DeterministicChunkIdsPlugin {
constructor(options?: {
context?: string;
maxLength?: number;
});
}
/**
* Generates deterministic module IDs based on module content and context
* @param options - Deterministic module ID options
*/
class DeterministicModuleIdsPlugin {
constructor(options?: {
context?: string;
maxLength?: number;
});
}
/**
* Uses human-readable names for chunk IDs in development
* @param options - Named chunk ID options
*/
class NamedChunkIdsPlugin {
constructor(options?: {
delimiter?: string;
context?: string;
});
}
/**
* Uses human-readable names for module IDs in development
* @param options - Named module ID options
*/
class NamedModuleIdsPlugin {
constructor(options?: {
context?: string;
});
}
/**
* Generates short hash-based module IDs for production
* @param options - Hash generation options
*/
class HashedModuleIdsPlugin {
constructor(options?: {
context?: string;
hashFunction?: string;
hashDigest?: string;
hashDigestLength?: number;
});
}
/**
* Uses natural numbers as module IDs (webpack 4 behavior)
*/
class NaturalModuleIdsPlugin {
constructor();
}Plugins enabling micro-frontend architectures through module federation capabilities.
/**
* Creates a container that exposes modules for consumption by other builds
* @param options - Container configuration
*/
class ContainerPlugin {
constructor(options: {
name: string;
library?: LibraryOptions;
filename?: string;
runtime?: string | false;
shareScope?: string;
exposes: { [key: string]: string };
});
}
/**
* Consumes modules from external containers
* @param options - Container reference configuration
*/
class ContainerReferencePlugin {
constructor(options: {
remoteType: string;
remotes: { [key: string]: string | string[] };
shareScope?: string;
});
}
/**
* Complete module federation setup combining container and reference functionality
* @param options - Module federation configuration
*/
class ModuleFederationPlugin {
constructor(options: {
name?: string;
filename?: string;
runtime?: string | false;
library?: LibraryOptions;
remoteType?: string;
remotes?: { [key: string]: string | string[] };
exposes?: { [key: string]: string };
shared?: { [key: string]: SharedConfig } | string[];
shareScope?: string;
});
}
/**
* Consumes shared modules from other builds
* @param options - Shared consumption configuration
*/
class ConsumeSharedPlugin {
constructor(options: {
consumes: { [key: string]: SharedConfig };
shareScope?: string;
});
}
/**
* Provides modules for sharing with other builds
* @param options - Shared provision configuration
*/
class ProvideSharedPlugin {
constructor(options: {
provides: { [key: string]: SharedConfig };
shareScope?: string;
});
}
/**
* Combines consume and provide shared functionality
* @param options - Share plugin configuration
*/
class SharePlugin {
constructor(options: {
shared: { [key: string]: SharedConfig };
shareScope?: string;
});
}Usage Examples:
const webpack = require("webpack");
// Host application
module.exports = {
plugins: [
new webpack.container.ModuleFederationPlugin({
name: 'host',
remotes: {
mf1: 'mf1@http://localhost:3001/remoteEntry.js'
},
shared: {
react: { singleton: true },
'react-dom': { singleton: true }
}
})
]
};
// Remote application
module.exports = {
plugins: [
new webpack.container.ModuleFederationPlugin({
name: 'mf1',
filename: 'remoteEntry.js',
exposes: {
'./Component': './src/Component'
},
shared: {
react: { singleton: true },
'react-dom': { singleton: true }
}
})
]
};Plugins that provide platform-specific functionality for web browsers, Node.js, Electron, and Web Workers.
// Web Platform Plugins
/**
* Enables JSONP-based chunk loading for web environments
* @param options - JSONP template options
*/
class JsonpTemplatePlugin {
constructor(options?: {
asyncChunkLoading?: boolean;
});
}
/**
* Enables WebAssembly compilation using fetch API for web
* @param options - Fetch WASM options
*/
class FetchCompileWasmPlugin {
constructor(options?: {
mangleImports?: boolean;
});
}
/**
* Enables async WebAssembly compilation for web environments
* @param options - Async WASM options
*/
class FetchCompileAsyncWasmPlugin {
constructor(options?: {
mangleImports?: boolean;
});
}
// Node.js Platform Plugins
/**
* Sets up Node.js environment for webpack builds
* @param options - Node environment options
*/
class NodeEnvironmentPlugin {
constructor(options?: {
infrastructureLogging?: any;
});
}
/**
* Handles Node.js built-in modules and polyfills
* @param options - Node source plugin options
*/
class NodeSourcePlugin {
constructor(options?: {
[key: string]: boolean | 'mock' | 'empty';
});
}
/**
* Configures build target for Node.js environments
* @param options - Node target options
*/
class NodeTargetPlugin {
constructor(options?: {
asyncChunkLoading?: boolean;
});
}
/**
* Provides Node.js-specific code generation templates
*/
class NodeTemplatePlugin {
constructor();
}
// Other Platform Plugins
/**
* Configures build for Electron applications (main and renderer processes)
* @param context - Target context ('main' | 'renderer' | 'preload')
*/
class ElectronTargetPlugin {
constructor(context?: 'main' | 'renderer' | 'preload');
}
/**
* Provides code generation templates for Web Worker environments
*/
class WebWorkerTemplatePlugin {
constructor();
}Plugins that manage entry points, chunk loading mechanisms, and module resolution.
/**
* Adds entry points to the compilation
* @param context - Entry context directory
* @param entry - Entry module path
* @param options - Entry configuration options
*/
class EntryPlugin {
constructor(context: string, entry: string, options?: string | EntryOptions);
}
/**
* Supports dynamically determined entry points
* @param context - Entry context directory
* @param entry - Function returning entry configuration
* @param options - Entry options
*/
class DynamicEntryPlugin {
constructor(
context: string,
entry: () => string | EntryObject | Promise<string | EntryObject>,
options?: string | EntryOptions
);
}
/**
* Processes and validates entry configuration from webpack config
* @param context - Base context directory
*/
class EntryOptionPlugin {
constructor(context?: string);
}
/**
* Enables JavaScript chunk loading mechanisms
* @param options - Chunk loading configuration
*/
class EnableChunkLoadingPlugin {
constructor(options: {
type: string;
enableAsync?: boolean;
});
}
/**
* Enables WebAssembly loading mechanisms
* @param options - WASM loading configuration
*/
class EnableWasmLoadingPlugin {
constructor(options: {
type: string;
});
}
/**
* Core JavaScript module processing and code generation
* @param options - JavaScript modules options
*/
class JavascriptModulesPlugin {
constructor(options?: {
chunkFormat?: string;
});
}Additional specialized plugins for CSS modules, library output, caching, and experimental features.
/**
* Provides support for CSS modules with local scope
* @param options - CSS modules configuration
*/
class CssModulesPlugin {
constructor(options?: {
localIdentName?: string;
namedExport?: boolean;
});
}
/**
* Abstract base class for library output plugins
*/
abstract class AbstractLibraryPlugin {
constructor(options: {
type: string;
});
}
/**
* Enables library output functionality
* @param type - Library output type
*/
class EnableLibraryPlugin {
constructor(type: string);
}
/**
* In-memory caching implementation for development
* @param options - Memory cache options
*/
class MemoryCachePlugin {
constructor(options?: {
maxGenerations?: number;
cacheUnaffected?: boolean;
});
}
/**
* Support for async WebAssembly modules
* @param options - Async WebAssembly options
*/
class AsyncWebAssemblyModulesPlugin {
constructor(options?: {
mangleImports?: boolean;
});
}
/**
* Experimental support for HTTP/HTTPS module resolution
* @param options - HTTP URI plugin options
*/
class HttpUriPlugin {
constructor(options?: {
allowedUris?: Array<string | RegExp | ((uri: string) => boolean)>;
cacheLocation?: string | false;
frozen?: boolean;
lockfileLocation?: string;
upgrade?: boolean;
});
}Essential plugins for DLL support, external modules, loader configuration, and build optimization.
/**
* Creates a DLL bundle for better build performance
* @param options - DLL plugin configuration
*/
class DllPlugin {
constructor(options: {
context?: string;
format?: boolean;
name: string;
path: string;
entryOnly?: boolean;
type?: string;
});
}
/**
* References a DLL bundle in the current build
* @param options - DLL reference configuration
*/
class DllReferencePlugin {
constructor(options: {
context?: string;
manifest: object | string;
content?: object;
name?: string;
scope?: string;
sourceType?: string;
type?: string;
});
}
/**
* Delegates module resolution to other webpack builds
* @param options - Delegation configuration
*/
class DelegatedPlugin {
constructor(options: {
source?: string;
type?: string;
context?: string;
content: object;
extensions?: string[];
});
}
/**
* Adds external dependencies without bundling them
* @param externals - External module configuration
*/
class ExternalsPlugin {
constructor(type: string, externals: ExternalItem | ExternalItem[]);
}
/**
* Configures loader options globally (deprecated in webpack 2+)
* @param options - Loader options
*/
class LoaderOptionsPlugin {
constructor(options: {
minimize?: boolean;
debug?: boolean;
options?: object;
[key: string]: any;
});
}
/**
* Sets the target environment for loaders
* @param target - Loader target environment
*/
class LoaderTargetPlugin {
constructor(target: string);
}
/**
* Prevents webpack from emitting assets when there are compilation errors
*/
class NoEmitOnErrorsPlugin {
constructor();
}
/**
* Automatically prefetch modules for better performance
* @param context - Module context
* @param request - Module request
*/
class AutomaticPrefetchPlugin {
constructor(context?: string, request?: string);
}
/**
* Manually prefetch modules
* @param context - Module context
* @param request - Module request
*/
class PrefetchPlugin {
constructor(context: string | null, request: string);
}
/**
* Creates a manifest file for DLL libraries
* @param options - Manifest generation options
*/
class LibManifestPlugin {
constructor(options?: {
context?: string;
format?: boolean;
name?: string;
path?: string;
type?: string;
});
}
/**
* Ignores files during the build process based on patterns
* @param paths - Glob patterns or RegExp for files to ignore during watching
*/
class WatchIgnorePlugin {
constructor(paths: (string | RegExp)[] | RegExp);
}
/**
* Adds a banner comment to the top of generated chunks
* @param options - Banner configuration
*/
class BannerPlugin {
constructor(options: string | {
banner: string | (() => string);
raw?: boolean;
entryOnly?: boolean;
test?: string | RegExp | (string | RegExp)[];
include?: string | RegExp | (string | RegExp)[];
exclude?: string | RegExp | (string | RegExp)[];
});
}
/**
* Sets the target platform for the build
* @param platform - Target platform
*/
class PlatformPlugin {
constructor(platform?: string);
}
/**
* Removes assets from the build that exceed size limits
* @param options - Size limit configuration
*/
class CleanPlugin {
constructor(options?: {
cleanStaleWebpackAssets?: boolean;
protectWebpackAssets?: boolean;
cleanOnceBeforeBuildPatterns?: string[];
cleanAfterEveryBuildPatterns?: string[];
dangerouslyAllowCleanPatternsOutsideProject?: boolean;
dry?: boolean;
verbose?: boolean;
});
}Plugins that are deprecated but still available for compatibility.
/**
* @deprecated Use SplitChunksPlugin instead
* Aggressively splits chunks for better caching
*/
class AggressiveSplittingPlugin {
constructor(options?: {
minSize?: number;
maxSize?: number;
chunkOverhead?: number;
entryChunkMultiplicator?: number;
});
}
/**
* @deprecated Use EntryPlugin instead
* Creates a single entry point (renamed to EntryPlugin)
*/
class SingleEntryPlugin {
constructor(context: string, entry: string, name?: string);
}
/**
* @deprecated Use compilation.outputOptions.library instead
* Template plugin for library output
*/
class LibraryTemplatePlugin {
constructor(name: any, target?: string, umdNamedDefine?: boolean, auxiliaryComment?: any, exportProperty?: string | string[]);
}interface WebpackPluginInstance {
apply(compiler: Compiler): void;
}
type WebpackPluginFunction = (compiler: Compiler) => void;
interface EntryOptions {
name?: string;
runtime?: string | false;
dependOn?: string | string[];
publicPath?: string;
chunkLoading?: ChunkLoadingType;
asyncChunks?: boolean;
wasmLoading?: WasmLoadingType;
library?: LibraryOptions;
}
interface SharedConfig {
shareKey?: string;
shareScope?: string;
version?: string | false;
singleton?: boolean;
strictVersion?: boolean;
requiredVersion?: string | false;
packageName?: string;
sharedName?: string;
eager?: boolean;
}
interface LibraryOptions {
name?: string | string[] | LibraryCustomUmdObject;
type?: string;
export?: string | string[];
auxiliaryComment?: string | LibraryCustomUmdCommentObject;
umdNamedDefine?: boolean;
}
type ChunkLoadingType = 'jsonp' | 'import-scripts' | 'require' | 'async-node' | 'import';
type WasmLoadingType = 'fetch-streaming' | 'fetch' | 'async-node' | 'sync';All webpack plugins implement the WebpackPluginInstance interface and use the compiler's hooks system for integration:
class CustomPlugin {
apply(compiler) {
compiler.hooks.compilation.tap('CustomPlugin', (compilation) => {
// Plugin logic using compilation hooks
compilation.hooks.processAssets.tap({
name: 'CustomPlugin',
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE
}, (assets) => {
// Process assets
});
});
}
}
module.exports = {
plugins: [
new CustomPlugin()
]
};The plugin system supports both class-based and function-based plugins, with class-based plugins being the recommended approach for complex functionality.
Install with Tessl CLI
npx tessl i tessl/npm-webpack