Skip to main content
The Compilation instance represents a single build of versioned assets. It provides access to all modules, chunks, and assets generated during the compilation process.

Accessing Compilation

The Compilation object is passed to plugins via the compilation hook:
class MyPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
      // Access compilation here
      console.log('Compilation created');
    });
  }
}

Properties

assets

Object containing all assets that will be emitted.
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
  // Access assets
  Object.keys(compilation.assets).forEach(filename => {
    console.log('Asset:', filename);
    console.log('Size:', compilation.assets[filename].size());
  });
  
  callback();
});

modules

Set of all modules in the compilation.
compilation.hooks.afterOptimizeModules.tap('MyPlugin', (modules) => {
  console.log(`Total modules: ${compilation.modules.size}`);
  
  for (const module of compilation.modules) {
    console.log('Module:', module.identifier());
  }
});

chunks

Set of all chunks in the compilation.
compilation.hooks.afterChunks.tap('MyPlugin', (chunks) => {
  console.log(`Total chunks: ${compilation.chunks.size}`);
  
  for (const chunk of compilation.chunks) {
    console.log('Chunk:', chunk.id, 'Files:', [...chunk.files]);
  }
});

errors

Array of errors that occurred during compilation.
compilation.hooks.afterSeal.tap('MyPlugin', () => {
  if (compilation.errors.length > 0) {
    console.error('Compilation errors:', compilation.errors);
  }
});

warnings

Array of warnings that occurred during compilation.
compilation.hooks.afterSeal.tap('MyPlugin', () => {
  if (compilation.warnings.length > 0) {
    console.warn('Compilation warnings:', compilation.warnings);
  }
});

moduleGraph

The ModuleGraph provides information about module dependencies.
compilation.hooks.finishModules.tap('MyPlugin', (modules) => {
  const moduleGraph = compilation.moduleGraph;
  
  for (const module of modules) {
    const exports = moduleGraph.getExportsInfo(module);
    console.log('Module exports:', exports);
  }
});

chunkGraph

The ChunkGraph provides information about chunk relationships.
compilation.hooks.afterChunks.tap('MyPlugin', () => {
  const chunkGraph = compilation.chunkGraph;
  
  for (const chunk of compilation.chunks) {
    const modules = chunkGraph.getChunkModules(chunk);
    console.log(`Chunk ${chunk.id} has ${modules.length} modules`);
  }
});

compiler

Reference to the parent Compiler instance.
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  console.log('Compiler context:', compilation.compiler.context);
});

options

Webpack configuration options.
compilation.hooks.seal.tap('MyPlugin', () => {
  console.log('Output path:', compilation.options.output.path);
  console.log('Mode:', compilation.options.mode);
});

Methods

addModule()

Adds a module to the compilation.
compilation.addModule(
  module: Module,
  callback: (err?: Error, module?: Module) => void
): void
module
Module
required
Module instance to add to the compilation.
callback
function
required
Callback invoked after the module is added.

getAssets()

Returns an array of all assets.
compilation.getAssets(): Asset[]
return
Asset[]
Array of asset objects with properties:
  • name (string) - Asset filename
  • source (Source) - Asset source
  • info (AssetInfo) - Asset metadata
Example:
compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  const assets = compilation.getAssets();
  
  assets.forEach(asset => {
    console.log('Asset:', asset.name);
    console.log('Size:', asset.info.size);
    console.log('Immutable:', asset.info.immutable);
  });
});

emitAsset()

Emits a new asset to the compilation.
compilation.emitAsset(
  file: string,
  source: Source,
  assetInfo?: AssetInfo
): void
file
string
required
Filename for the asset.
source
Source
required
Source object (from webpack-sources).
assetInfo
AssetInfo
Optional metadata about the asset.
Example:
const { RawSource } = require('webpack-sources');

compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  const content = JSON.stringify({
    hash: compilation.hash,
    version: require('./package.json').version
  });
  
  compilation.emitAsset(
    'manifest.json',
    new RawSource(content),
    {
      size: content.length,
      development: false
    }
  );
});

updateAsset()

Updates an existing asset.
compilation.updateAsset(
  file: string,
  newSourceOrFunction: Source | ((source: Source) => Source),
  assetInfoUpdateOrFunction?: AssetInfo | ((assetInfo: AssetInfo) => AssetInfo)
): void
file
string
required
Filename of the asset to update.
newSourceOrFunction
Source | function
required
New source or function that transforms the existing source.
assetInfoUpdateOrFunction
AssetInfo | function
New asset info or function that updates the existing info.
Example:
const { RawSource } = require('webpack-sources');

compiler.hooks.processAssets.tap({
  name: 'MyPlugin',
  stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE
}, (compilation) => {
  for (const filename in compilation.assets) {
    if (filename.endsWith('.js')) {
      compilation.updateAsset(
        filename,
        (source) => {
          const content = source.source();
          const minified = minifyCode(content);
          return new RawSource(minified);
        }
      );
    }
  }
});

deleteAsset()

Deletes an asset from the compilation.
compilation.deleteAsset(file: string): void
file
string
required
Filename of the asset to delete.
Example:
compiler.hooks.emit.tap('MyPlugin', (compilation) => {
  // Remove source maps in production
  if (compilation.options.mode === 'production') {
    Object.keys(compilation.assets).forEach(filename => {
      if (filename.endsWith('.map')) {
        compilation.deleteAsset(filename);
      }
    });
  }
});

getLogger()

Returns a logger for the compilation.
compilation.getLogger(name: string | (() => string)): Logger
name
string | function
required
Logger name or function returning the logger name.
return
Logger
Logger instance for logging compilation events.
Example:
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  const logger = compilation.getLogger('MyPlugin');
  
  logger.log('Plugin initialized');
  logger.warn('Potential issue detected');
  logger.time('optimization');
  // ... do optimization
  logger.timeEnd('optimization');
});

getPath()

Interpolates a template path with compilation data.
compilation.getPath(
  filename: string,
  data?: PathData
): string
filename
string
required
Template string with placeholders like [name], [hash], [chunkhash].
data
PathData
Data used for interpolation (chunk, module, etc).
return
string
Interpolated path string.
Example:
compilation.hooks.afterSeal.tap('MyPlugin', () => {
  const outputPath = compilation.getPath('[name].[contenthash].js', {
    chunk: compilation.chunks.values().next().value
  });
  
  console.log('Output path:', outputPath);
});

Compilation Hooks

Compilation provides many hooks for different stages of the build process.

buildModule

Called before a module is built.
compilation.hooks.buildModule.tap('MyPlugin', (module) => {
  console.log('Building module:', module.identifier());
});

succeedModule

Called after a module has been built successfully.
compilation.hooks.succeedModule.tap('MyPlugin', (module) => {
  console.log('Module built successfully:', module.identifier());
});

seal

Called when compilation stops accepting new modules.
compilation.hooks.seal.tap('MyPlugin', () => {
  console.log('Compilation sealed, optimizing...');
});

optimize

Called at the beginning of the optimization phase.
compilation.hooks.optimize.tap('MyPlugin', () => {
  console.log('Starting optimization...');
});

optimizeModules

Called during module optimization.
compilation.hooks.optimizeModules.tap('MyPlugin', (modules) => {
  console.log('Optimizing modules...');
  // Optimize modules
});

optimizeChunks

Called during chunk optimization.
compilation.hooks.optimizeChunks.tap('MyPlugin', (chunks) => {
  console.log('Optimizing chunks...');
  // Optimize chunks
});

processAssets

Called during asset processing. This is the main hook for asset optimization.
compilation.hooks.processAssets.tap({
  name: 'MyPlugin',
  stage: Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE
}, (assets) => {
  for (const name in assets) {
    console.log('Processing asset:', name);
  }
});
Asset processing stages:
  • PROCESS_ASSETS_STAGE_ADDITIONAL - Add additional assets
  • PROCESS_ASSETS_STAGE_PRE_PROCESS - Basic preprocessing
  • PROCESS_ASSETS_STAGE_DERIVED - Derive assets from existing
  • PROCESS_ASSETS_STAGE_ADDITIONS - Add additional assets
  • PROCESS_ASSETS_STAGE_OPTIMIZE - Optimize existing assets
  • PROCESS_ASSETS_STAGE_OPTIMIZE_COUNT - Optimize asset count
  • PROCESS_ASSETS_STAGE_OPTIMIZE_COMPATIBILITY - Optimize compatibility
  • PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE - Optimize asset size
  • PROCESS_ASSETS_STAGE_DEV_TOOLING - Add development tooling
  • PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE - Optimize for inlining
  • PROCESS_ASSETS_STAGE_SUMMARIZE - Summarize assets
  • PROCESS_ASSETS_STAGE_OPTIMIZE_HASH - Optimize asset hashes
  • PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER - Optimize for transfer
  • PROCESS_ASSETS_STAGE_ANALYSE - Analyze assets
  • PROCESS_ASSETS_STAGE_REPORT - Report asset information

afterProcessAssets

Called after all assets have been processed.
compilation.hooks.afterProcessAssets.tap('MyPlugin', (assets) => {
  console.log('All assets processed');
});

Complete Example: Asset Generation Plugin

const { RawSource } = require('webpack-sources');

class AssetGenerationPlugin {
  apply(compiler) {
    compiler.hooks.compilation.tap('AssetGenerationPlugin', (compilation) => {
      compilation.hooks.processAssets.tap({
        name: 'AssetGenerationPlugin',
        stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL
      }, (assets) => {
        // Generate a manifest of all assets
        const manifest = {
          hash: compilation.hash,
          time: new Date().toISOString(),
          assets: Object.keys(assets).map(filename => ({
            name: filename,
            size: assets[filename].size(),
            chunks: []
          }))
        };
        
        const manifestSource = JSON.stringify(manifest, null, 2);
        
        compilation.emitAsset(
          'assets-manifest.json',
          new RawSource(manifestSource),
          {
            size: manifestSource.length
          }
        );
      });
      
      compilation.hooks.afterProcessAssets.tap(
        'AssetGenerationPlugin',
        () => {
          const logger = compilation.getLogger('AssetGenerationPlugin');
          logger.log(`Generated manifest with ${compilation.getAssets().length} assets`);
        }
      );
    });
  }
}

module.exports = AssetGenerationPlugin;

See Also