> ## 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.

# Compiler API

> webpack Compiler class API - hooks, methods, and properties

The Compiler instance represents the fully configured webpack environment. It's created once when webpack is started and contains all the configuration, loaders, plugins, and resolver settings.

## Creating a Compiler

The Compiler is created when you call the `webpack()` function:

```javascript theme={null}
const webpack = require('webpack');
const config = require('./webpack.config.js');

const compiler = webpack(config);
```

## Methods

### run()

Runs a single build. The callback is called when the compilation completes.

```typescript theme={null}
compiler.run(
  callback: (err: Error | null, stats?: Stats) => void
): void
```

<ParamField path="callback" type="function" required>
  Callback invoked when the compilation completes.

  **Parameters:**

  * `err` - Error object if compilation failed, null otherwise
  * `stats` - Stats object containing compilation results
</ParamField>

**Example:**

```javascript theme={null}
compiler.run((err, stats) => {
  if (err) {
    console.error(err);
    return;
  }
  
  console.log(stats.toString({
    colors: true,
    chunks: false
  }));
  
  // Always close the compiler when done
  compiler.close((closeErr) => {
    if (closeErr) {
      console.error('Failed to close compiler:', closeErr);
    }
  });
});
```

### watch()

Runs webpack in watch mode. Watches for file changes and recompiles automatically.

```typescript theme={null}
compiler.watch(
  watchOptions: WatchOptions,
  handler: (err: Error | null, stats?: Stats) => void
): Watching
```

<ParamField path="watchOptions" type="WatchOptions" required>
  Watch configuration options.

  **Properties:**

  * `aggregateTimeout` (number) - Delay before rebuilding (default: 300ms)
  * `poll` (number | boolean) - Enable polling and set interval in ms
  * `ignored` (string | RegExp | string\[]) - Paths to ignore
</ParamField>

<ParamField path="handler" type="function" required>
  Callback invoked after each compilation.
</ParamField>

<ResponseField name="return" type="Watching">
  Returns a Watching instance that can be used to stop watching.
</ResponseField>

**Example:**

```javascript theme={null}
const watching = compiler.watch({
  aggregateTimeout: 300,
  poll: undefined,
  ignored: /node_modules/
}, (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }
  
  console.log('Recompiled:', new Date().toLocaleTimeString());
  console.log(stats.toString({ colors: true }));
});

// Later: stop watching
watching.close((closeErr) => {
  console.log('Watching closed.');
});
```

### close()

Closes the compiler and releases resources. Should always be called after `run()` completes.

```typescript theme={null}
compiler.close(
  callback: (err?: Error) => void
): void
```

<ParamField path="callback" type="function" required>
  Callback invoked when the compiler is closed.
</ParamField>

**Example:**

```javascript theme={null}
compiler.run((err, stats) => {
  // Process results...
  
  compiler.close((closeErr) => {
    if (closeErr) {
      console.error('Error closing compiler:', closeErr);
    }
    console.log('Compiler closed.');
  });
});
```

### getCache()

Returns a cache facade for the specified cache name.

```typescript theme={null}
compiler.getCache(name: string): CacheFacade
```

<ParamField path="name" type="string" required>
  Unique name for the cache.
</ParamField>

<ResponseField name="return" type="CacheFacade">
  Cache facade instance for storing and retrieving cached data.
</ResponseField>

**Example:**

```javascript theme={null}
const cache = compiler.getCache('my-plugin');

// Store data
cache.store('key', null, data, (err) => {
  if (err) console.error(err);
});

// Retrieve data
cache.get('key', null, (err, result) => {
  if (err) console.error(err);
  console.log('Cached data:', result);
});
```

### getInfrastructureLogger()

Returns a logger for infrastructure logging.

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

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

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

**Example:**

```javascript theme={null}
const logger = compiler.getInfrastructureLogger('my-plugin');

logger.log('Plugin initialized');
logger.warn('Potential issue detected');
logger.error('Critical error occurred');
```

## Properties

### options

The webpack configuration options used to create this compiler.

```javascript theme={null}
const compiler = webpack(config);
console.log(compiler.options.entry);
console.log(compiler.options.output);
```

### hooks

Tapable hooks for the compilation process. See [Compiler Hooks](#compiler-hooks) section.

```javascript theme={null}
compiler.hooks.done.tap('MyPlugin', (stats) => {
  console.log('Compilation complete!');
});
```

### outputFileSystem

The file system used for writing output files.

```javascript theme={null}
const fs = require('fs');
compiler.outputFileSystem = fs;
```

### inputFileSystem

The file system used for reading input files.

```javascript theme={null}
compiler.inputFileSystem = require('fs');
```

### resolverFactory

Factory for creating module resolvers.

```javascript theme={null}
const resolver = compiler.resolverFactory.get('normal');
```

## Compiler Hooks

The Compiler exposes hooks for plugins to tap into various stages of the compilation lifecycle.

### run

Called before a new compilation is started.

```javascript theme={null}
compiler.hooks.run.tapAsync('MyPlugin', (compiler, callback) => {
  console.log('Starting compilation...');
  callback();
});
```

### compile

Called before a new compilation is created.

```javascript theme={null}
compiler.hooks.compile.tap('MyPlugin', (params) => {
  console.log('Creating compilation...');
});
```

### compilation

Called after a new compilation is created.

```javascript theme={null}
compiler.hooks.compilation.tap('MyPlugin', (compilation, params) => {
  console.log('Compilation created');
  
  // Access compilation hooks
  compilation.hooks.optimize.tap('MyPlugin', () => {
    console.log('Optimizing...');
  });
});
```

### make

Called during the compilation phase when modules are being processed.

```javascript theme={null}
compiler.hooks.make.tapAsync('MyPlugin', (compilation, callback) => {
  console.log('Processing modules...');
  callback();
});
```

### emit

Called before assets are written to output directory.

```javascript theme={null}
compiler.hooks.emit.tapAsync('MyPlugin', (compilation, callback) => {
  // Modify or add assets
  compilation.assets['custom-file.txt'] = {
    source: () => 'Custom content',
    size: () => 14
  };
  callback();
});
```

### afterEmit

Called after assets have been written to output directory.

```javascript theme={null}
compiler.hooks.afterEmit.tapAsync('MyPlugin', (compilation, callback) => {
  console.log('Assets emitted to disk');
  callback();
});
```

### done

Called when compilation completes successfully.

```javascript theme={null}
compiler.hooks.done.tap('MyPlugin', (stats) => {
  const json = stats.toJson();
  console.log('Build time:', json.time, 'ms');
  console.log('Hash:', json.hash);
});
```

### failed

Called when compilation fails.

```javascript theme={null}
compiler.hooks.failed.tap('MyPlugin', (error) => {
  console.error('Compilation failed:', error.message);
});
```

### invalid

Called when watch compilation is invalidated.

```javascript theme={null}
compiler.hooks.invalid.tap('MyPlugin', (fileName, changeTime) => {
  console.log(`File changed: ${fileName} at ${new Date(changeTime)}`);
});
```

### watchRun

Called before a watch compilation starts.

```javascript theme={null}
compiler.hooks.watchRun.tapAsync('MyPlugin', (compiler, callback) => {
  console.log('Watch compilation starting...');
  callback();
});
```

## Complete Example: Custom Plugin

```javascript theme={null}
class MyCustomPlugin {
  apply(compiler) {
    const pluginName = 'MyCustomPlugin';
    
    // Tap into compilation creation
    compiler.hooks.compilation.tap(pluginName, (compilation) => {
      console.log('New compilation created');
    });
    
    // Tap into the emit phase
    compiler.hooks.emit.tapAsync(pluginName, (compilation, callback) => {
      // Create a custom asset
      const buildTime = new Date().toString();
      compilation.assets['build-time.txt'] = {
        source: () => buildTime,
        size: () => buildTime.length
      };
      
      callback();
    });
    
    // Tap into the done hook
    compiler.hooks.done.tap(pluginName, (stats) => {
      console.log('Compilation finished!');
      console.log('Hash:', stats.compilation.hash);
      console.log('Time:', stats.endTime - stats.startTime, 'ms');
    });
  }
}

module.exports = MyCustomPlugin;
```

## See Also

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