TheCompilation module is used by theCompiler to create new compilations(or builds). Acompilation instance has access to all modules and theirdependencies (most of which are circular references). It is the literalcompilation of all the modules in the dependency graph of an application.During the compilation phase, modules are loaded, sealed, optimized, chunked,hashed and restored.
TheCompilation class also extendsTapable and provides the followinglifecycle hooks. They can be tapped the same way as compiler hooks:
compilation.hooks.someHook.tap(/* ... */);As with thecompiler,tapAsync andtapPromise may also be availabledepending on the type of hook.
Since webpack 5,hooks are no longer extendable. Use aWeakMap to add custom hooks.
SyncHook
Triggered before a module build has started, can be used to modify the module.
modulecompilation.hooks.buildModule.tap('SourceMapDevToolModuleOptionsPlugin',(module)=>{ module.useSourceMap=true;});SyncHook
Fired before rebuilding a module.
moduleSyncHook
Run when a module build has failed.
moduleerrorSyncHook
Executed when a module has been built successfully.
moduleAsyncSeriesHook
Called when all modules have been built without errors.
modulesSyncHook
Executed when a module has been rebuilt, in case of both success or with errors.
moduleSyncHook
Fired when the compilation stops accepting new modules.
SyncHook
Fired when a compilation begins accepting new modules.
SyncBailHook
Fired at the beginning of dependency optimization.
modulesSyncHook
Fired after the dependency optimization.
modulesSyncHook
TheafterChunks hook is invoked following the creation of the chunks and module graph, and prior to their optimization.This hook provides an opportunity to examine, analyze, and modify the chunk graph if necessary.
Here'san example of how to utilize thecompilation.hooks.afterChunks hook.
chunksSyncHook
Triggered at the beginning of the optimization phase.
SyncBailHook
Called at the beginning of the module optimization phase. A plugin can tap into this hook to perform optimizations on modules.
modulesSyncHook
Called after modules optimization has completed.
modulesSyncBailHook
Called at the beginning of the chunk optimization phase. A plugin can tap into this hook to perform optimizations on chunks.
chunksSyncHook
Fired after chunk optimization has completed.
chunksAsyncSeriesHook
Called before optimizing the dependency tree. A plugin can tap into this hook to perform a dependency tree optimization.
chunksmodulesSyncHook
Called after the dependency tree optimization has completed with success.
chunksmodulesSyncBailHook
Called after the tree optimization, at the beginning of the chunk modules optimization. A plugin can tap into this hook to perform optimizations of chunk modules.
chunksmodulesSyncHook
Called after the chunkmodules optimization has completed successfully.
chunksmodulesSyncBailHook
Called to determine whether or not to store records. Returning anything!== false will prevent every other "record" hook from being executed (record,recordModules,recordChunks andrecordHash).
SyncHook
Restore module information from records.
modulesrecordsSyncHook
Executed before assigning anid to each module.
modulesSyncHook
Called to assign anid to each module.
modulesSyncHook
Called at the beginning of the modulesid optimization.
modulesSyncHook
Called when the modulesid optimization phase has completed.
modulesSyncHook
Restore chunk information from records.
chunksrecordsSyncHook
Executed before assigning anid to each chunk.
chunksSyncHook
Called to assign anid to each chunk.
chunksSyncHook
Called at the beginning of the chunksid optimization phase.
chunksSyncHook
Triggered after chunkid optimization has finished.
chunksSyncHook
Store module info to the records. This is triggered ifshouldRecord returns a truthy value.
modulesrecordsSyncHook
Store chunk info to the records. This is only triggered ifshouldRecord returns a truthy value.
chunksrecordsSyncHook
Called before modules are hashed.
syncHook
Called after modules are hashed.
SyncHook
Called before the compilation is hashed.
SyncHook
Called after the compilation is hashed.
SyncHook
Store information about record hash to therecords. This is only triggered ifshouldRecord returns a truthy value.
recordsSyncHook
Store information about thecompilation to therecords. This is only triggered ifshouldRecord returns a truthy value.
compilationrecordsSyncHook
Executed before module assets creation.
SyncHook
additionalChunkAssets is deprecated (use theCompilation.hook.processAssets instead and use one of the Compilation.PROCESS_ASSETS_STAGE_* as a stage option)
Create additional assets for the chunks.
chunksSyncBailHook
Called to determine whether or not generate chunks assets. Returning anything!== false will allow chunk assets generation.
SyncHook
Executed before creating the chunks assets.
AsyncSeriesHook
additionalAssets is deprecated (use theCompilation.hook.processAssets hook instead and use one of the Compilation.PROCESS_ASSETS_STAGE_* as a stage option)
Create additional assets for the compilation. This hook can be used to downloadan image, for example:
compilation.hooks.additionalAssets.tapAsync('MyPlugin',(callback)=>{download('https://img.shields.io/npm/v/webpack.svg',function(resp){if(resp.status===200){ compilation.assets['webpack-version.svg']=toAsset(resp);callback();}else{callback(newError('[webpack-example-plugin] Unable to download the image'));}});});AsyncSeriesHook
optimizeChunkAssets is deprecated (use theCompilation.hook.processAssets instead and use one of the Compilation.PROCESS_ASSETS_STAGE_* as a stage option)
Optimize any chunk assets. The assets are stored incompilation.assets. AChunk has a propertyfiles which points to all files created by a chunk.Any additional chunk assets are stored incompilation.additionalChunkAssets.
chunksHere's an example that adds a banner to each chunk.
compilation.hooks.optimizeChunkAssets.tapAsync('MyPlugin',(chunks, callback)=>{ chunks.forEach((chunk)=>{ chunk.files.forEach((file)=>{ compilation.assets[file]=newConcatSource('/**Sweet Banner**/','\n', compilation.assets[file]);});});callback();});SyncHook
afterOptimizeChunkAssets is deprecated (use theCompilation.hook.processAssets instead and use one of the Compilation.PROCESS_ASSETS_STAGE_* as a stage option)
The chunk assets have been optimized.
chunksHere's an example plugin from@boopathi that outputs exactly what went into each chunk.
compilation.hooks.afterOptimizeChunkAssets.tap('MyPlugin',(chunks)=>{ chunks.forEach((chunk)=>{ console.log({ id: chunk.id, name: chunk.name, includes: chunk.getModules().map((module)=> module.request),});});});AsyncSeriesHook
optimizeAssets is deprecated (use theCompilation.hook.processAssets hook instead)
Optimize all assets stored incompilation.assets.
assetsSyncHook
afterOptimizeAssets is deprecated (use theCompilation.hook.afterProcessAssets hook instead)
The assets have been optimized.
assetsAsyncSeriesHook
Asset processing.
Hook parameters:
name: string — a name of the pluginstage: Stage — a stage to tap into (see thelist of supported stages below)additionalAssets?: true | (assets, [callback]) => (void | Promise<void>) — a callback for additional assets (see below)Callback parameters:
assets: { [pathname: string]: Source } — a plain object, where key is the asset's pathname, and the value is data of the asset represented by theSource.Example:
compilation.hooks.processAssets.tap({ name:'MyPlugin', stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS,// see below for more stages},(assets)=>{ console.log('List of assets and their sizes:'); Object.entries(assets).forEach(([pathname, source])=>{ console.log(`—${pathname}:${source.size()} bytes`);});});In addition toname andstage, you can pass anadditionalAssets5.8.0+ option which accepts either a value oftrue or a callback function that receivesassets as a first argument:
true — run the provided callback again for assets added later by plugins.
In this mode, the callback will be called multiple times: once for assets added prior to the specified stage, and additional times for assets added by plugins later (on this or next stages).
compilation.hooks.processAssets.tap({ name:'MyPlugin', stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING, additionalAssets:true,},(assets)=>{// this function will be called multiple times with each bulk of assets});(assets, [callback]) => (void | Promise<void>) — run the specified callback against assets added by plugins later (on this or next stages). The callback must respect the type of the tap method used (e.g. when used withtapPromise(), it should return a promise).
compilation.hooks.processAssets.tap({ name:'MyPlugin', stage: Compilation.PROCESS_ASSETS_STAGE_DEV_TOOLING,additionalAssets:(assets)=>{// this function potentially could be called multiple times for assets added on later stages},},(assets)=>{// this function will be called once with assets added by plugins on prior stages});Here's a list of supported stages (in the order of processing):
PROCESS_ASSETS_STAGE_ADDITIONAL — add additional assets to the compilation.PROCESS_ASSETS_STAGE_PRE_PROCESS — basic preprocessing of the assets.PROCESS_ASSETS_STAGE_DERIVED — derive new assets from the existing assets.PROCESS_ASSETS_STAGE_ADDITIONS — add additional sections to the existing assets e.g. banner or initialization code.PROCESS_ASSETS_STAGE_OPTIMIZE — optimize existing assets in a general way.PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT — optimize the count of existing assets, e.g. by merging them.PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY — optimize the compatibility of existing assets, e.g. add polyfills or vendor prefixes.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE — optimize the size of existing assets, e.g. by minimizing or omitting whitespace.PROCESS_ASSETS_STAGE_DEV_TOOLING — add development tooling to the assets, e.g. by extracting a source map.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE5.8.0+ — optimize the numbers of existing assets, e.g. by inlining assets into other assets.PROCESS_ASSETS_STAGE_SUMMARIZE — summarize the list of existing assets.PROCESS_ASSETS_STAGE_OPTIMIZE_HASH — optimize the hashes of the assets, e.g. by generating real hashes of the asset content.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER — optimize the transfer of existing assets, e.g. by preparing a compressed (gzip) file as separate asset.PROCESS_ASSETS_STAGE_ANALYSE — analyze the existing assets.PROCESS_ASSETS_STAGE_REPORT — creating assets for the reporting purposes.The "asset info" metadata is not automatically provided for this hook. If needed, you will have to resolve this metadata manually using the compilation instance and the provided asset pathname. This will be improved in a future version of the webpack.
Example:
compilation.hooks.processAssets.tap({/** … */},(assets)=>{ Object.entries(assets).forEach(([pathname, source])=>{const assetInfo= compilation.assetsInfo.get(pathname);// @todo: do something with "pathname", "source" and "assetInfo"});});SyncHook
Called after theprocessAssets hook had finished without error.
SyncBailHook
Called to determine if the compilation needs to be unsealed to include other files.
AsyncSeriesHook
Executed right afterneedAdditionalSeal.
SyncHook
Triggered to emit the hash for each chunk.
chunkchunkHashSyncHook
Called when an asset from a module was added to the compilation.
modulefilenameSyncHook
Triggered when an asset from a chunk was added to the compilation.
chunkfilenameSyncWaterfallHook
Called to determine the path of an asset.
pathoptionsSyncBailHook
Called to determine if an asset needs to be processed further after being emitted.
SyncHook
Executed after setting up a child compiler.
childCompilercompilerNamecompilerIndexSince webpack v5normalModuleLoader hook was removed. Now to access the loader useNormalModule.getCompilationHooks(compilation).loader instead.
HookMap
This HookMap is like a list of actions that gets triggered when a preset is used. It takes in an options object. When a plugin manages a preset, it should change settings in this object carefully without replacing existing ones.
optionscontextHere's an illustrative plugin example:
compilation.hooks.statsPreset.for('my-preset').tap('MyPlugin',(options)=>{if(options.all===undefined) options.all=true;});This plugin ensures that for the preset'my-preset', if theall option is undefined, it defaults to true.
SyncHook
This hook is used to transform an options object into a consistent format that can be easily used by subsequent hooks. It also ensures that missing options are set to their default values.
optionscontextHere's an illustrative plugin example:
compilation.hooks.statsNormalize.tap('MyPlugin',(options)=>{if(options.myOption===undefined) options.myOption=[];if(!Array.isArray(options.myOption)) options.myOptions=[options.myOptions];});In this plugin, if themyOption is missing, it sets it to an empty array. Additionally, it ensures thatmyOption is always an array even if it was originally defined as a single value.
This hook provides access to theStatsFactory class for specific options.
statsFactoryoptionsHookMap
objectdatacontextdata contains the class. object is an object to which properties should be added.context provides contextual information, such as classes on the path.
Example:
compilation.hooks.statsFactory.tap('MyPlugin',(statsFactory, options)=>{ statsFactory.hooks.extract.for('compilation').tap('MyPlugin',(object, compilation)=>{ object.customProperty= MyPlugin.getCustomValue(compilation);});});HookMap
Called with the result on each level.
resultcontextThis hook provides access to theStatsPrinter class for specific options.
statsPrinteroptionsHookMap
This hook is called when a part should be printed.
objectcontextHookMap
This hook is called for the resulting string for a part.
resultcontext