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.
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:
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.
compiler.run(
callback: (err: Error | null, stats?: Stats) => void
): void
Callback invoked when the compilation completes.Parameters:
err - Error object if compilation failed, null otherwise
stats - Stats object containing compilation results
Example:
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.
compiler.watch(
watchOptions: WatchOptions,
handler: (err: Error | null, stats?: Stats) => void
): Watching
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
Callback invoked after each compilation.
Returns a Watching instance that can be used to stop watching.
Example:
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.
compiler.close(
callback: (err?: Error) => void
): void
Callback invoked when the compiler is closed.
Example:
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.
compiler.getCache(name: string): CacheFacade
Unique name for the cache.
Cache facade instance for storing and retrieving cached data.
Example:
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.
compiler.getInfrastructureLogger(
name: string | (() => string)
): Logger
name
string | function
required
Logger name or function that returns the logger name.
Logger instance for logging infrastructure events.
Example:
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.
const compiler = webpack(config);
console.log(compiler.options.entry);
console.log(compiler.options.output);
hooks
Tapable hooks for the compilation process. See Compiler Hooks section.
compiler.hooks.done.tap('MyPlugin', (stats) => {
console.log('Compilation complete!');
});
outputFileSystem
The file system used for writing output files.
const fs = require('fs');
compiler.outputFileSystem = fs;
The file system used for reading input files.
compiler.inputFileSystem = require('fs');
resolverFactory
Factory for creating module resolvers.
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.
compiler.hooks.run.tapAsync('MyPlugin', (compiler, callback) => {
console.log('Starting compilation...');
callback();
});
compile
Called before a new compilation is created.
compiler.hooks.compile.tap('MyPlugin', (params) => {
console.log('Creating compilation...');
});
compilation
Called after a new compilation is created.
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.
compiler.hooks.make.tapAsync('MyPlugin', (compilation, callback) => {
console.log('Processing modules...');
callback();
});
emit
Called before assets are written to output directory.
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.
compiler.hooks.afterEmit.tapAsync('MyPlugin', (compilation, callback) => {
console.log('Assets emitted to disk');
callback();
});
done
Called when compilation completes successfully.
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.
compiler.hooks.failed.tap('MyPlugin', (error) => {
console.error('Compilation failed:', error.message);
});
invalid
Called when watch compilation is invalidated.
compiler.hooks.invalid.tap('MyPlugin', (fileName, changeTime) => {
console.log(`File changed: ${fileName} at ${new Date(changeTime)}`);
});
watchRun
Called before a watch compilation starts.
compiler.hooks.watchRun.tapAsync('MyPlugin', (compiler, callback) => {
console.log('Watch compilation starting...');
callback();
});
Complete Example: Custom Plugin
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