> ## Documentation Index
> Fetch the complete documentation index at: https://docs.webpack.js.org/llms.txt
> Use this file to discover all available pages before exploring further.

# Compilation API

> webpack Compilation class API - assets, modules, chunks, and hooks

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:

```javascript theme={null}
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.

```javascript theme={null}
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.

```javascript theme={null}
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.

```javascript theme={null}
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.

```javascript theme={null}
compilation.hooks.afterSeal.tap('MyPlugin', () => {
  if (compilation.errors.length > 0) {
    console.error('Compilation errors:', compilation.errors);
  }
});
```

### warnings

Array of warnings that occurred during compilation.

```javascript theme={null}
compilation.hooks.afterSeal.tap('MyPlugin', () => {
  if (compilation.warnings.length > 0) {
    console.warn('Compilation warnings:', compilation.warnings);
  }
});
```

### moduleGraph

The ModuleGraph provides information about module dependencies.

```javascript theme={null}
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.

```javascript theme={null}
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.

```javascript theme={null}
compiler.hooks.compilation.tap('MyPlugin', (compilation) => {
  console.log('Compiler context:', compilation.compiler.context);
});
```

### options

Webpack configuration options.

```javascript theme={null}
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.

```typescript theme={null}
compilation.addModule(
  module: Module,
  callback: (err?: Error, module?: Module) => void
): void
```

<ParamField path="module" type="Module" required>
  Module instance to add to the compilation.
</ParamField>

<ParamField path="callback" type="function" required>
  Callback invoked after the module is added.
</ParamField>

### getAssets()

Returns an array of all assets.

```typescript theme={null}
compilation.getAssets(): Asset[]
```

<ResponseField name="return" type="Asset[]">
  Array of asset objects with properties:

  * `name` (string) - Asset filename
  * `source` (Source) - Asset source
  * `info` (AssetInfo) - Asset metadata
</ResponseField>

**Example:**

```javascript theme={null}
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.

```typescript theme={null}
compilation.emitAsset(
  file: string,
  source: Source,
  assetInfo?: AssetInfo
): void
```

<ParamField path="file" type="string" required>
  Filename for the asset.
</ParamField>

<ParamField path="source" type="Source" required>
  Source object (from webpack-sources).
</ParamField>

<ParamField path="assetInfo" type="AssetInfo">
  Optional metadata about the asset.
</ParamField>

**Example:**

```javascript theme={null}
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.

```typescript theme={null}
compilation.updateAsset(
  file: string,
  newSourceOrFunction: Source | ((source: Source) => Source),
  assetInfoUpdateOrFunction?: AssetInfo | ((assetInfo: AssetInfo) => AssetInfo)
): void
```

<ParamField path="file" type="string" required>
  Filename of the asset to update.
</ParamField>

<ParamField path="newSourceOrFunction" type="Source | function" required>
  New source or function that transforms the existing source.
</ParamField>

<ParamField path="assetInfoUpdateOrFunction" type="AssetInfo | function">
  New asset info or function that updates the existing info.
</ParamField>

**Example:**

```javascript theme={null}
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.

```typescript theme={null}
compilation.deleteAsset(file: string): void
```

<ParamField path="file" type="string" required>
  Filename of the asset to delete.
</ParamField>

**Example:**

```javascript theme={null}
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.

```typescript theme={null}
compilation.getLogger(name: string | (() => string)): Logger
```

<ParamField path="name" type="string | function" required>
  Logger name or function returning the logger name.
</ParamField>

<ResponseField name="return" type="Logger">
  Logger instance for logging compilation events.
</ResponseField>

**Example:**

```javascript theme={null}
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.

```typescript theme={null}
compilation.getPath(
  filename: string,
  data?: PathData
): string
```

<ParamField path="filename" type="string" required>
  Template string with placeholders like \[name], \[hash], \[chunkhash].
</ParamField>

<ParamField path="data" type="PathData">
  Data used for interpolation (chunk, module, etc).
</ParamField>

<ResponseField name="return" type="string">
  Interpolated path string.
</ResponseField>

**Example:**

```javascript theme={null}
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.

```javascript theme={null}
compilation.hooks.buildModule.tap('MyPlugin', (module) => {
  console.log('Building module:', module.identifier());
});
```

### succeedModule

Called after a module has been built successfully.

```javascript theme={null}
compilation.hooks.succeedModule.tap('MyPlugin', (module) => {
  console.log('Module built successfully:', module.identifier());
});
```

### seal

Called when compilation stops accepting new modules.

```javascript theme={null}
compilation.hooks.seal.tap('MyPlugin', () => {
  console.log('Compilation sealed, optimizing...');
});
```

### optimize

Called at the beginning of the optimization phase.

```javascript theme={null}
compilation.hooks.optimize.tap('MyPlugin', () => {
  console.log('Starting optimization...');
});
```

### optimizeModules

Called during module optimization.

```javascript theme={null}
compilation.hooks.optimizeModules.tap('MyPlugin', (modules) => {
  console.log('Optimizing modules...');
  // Optimize modules
});
```

### optimizeChunks

Called during chunk optimization.

```javascript theme={null}
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.

```javascript theme={null}
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.

```javascript theme={null}
compilation.hooks.afterProcessAssets.tap('MyPlugin', (assets) => {
  console.log('All assets processed');
});
```

## Complete Example: Asset Generation Plugin

```javascript theme={null}
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

* [Compiler API](/api/compiler) - Compiler instance methods
* [Stats Object](/api/stats) - Compilation statistics
* [Compilation Hooks](https://webpack.js.org/api/compilation-hooks/) - Full list of hooks
