Clean Webpack Plugin is a webpack plugin that automatically removes/cleans build folders and unused webpack assets. It provides comprehensive configuration options for controlling when and what files are cleaned, including dry-run capabilities, verbose logging, and pattern-based file matching for precise control over file removal.
npm install --save-dev clean-webpack-pluginimport { CleanWebpackPlugin } from "clean-webpack-plugin";For CommonJS:
const { CleanWebpackPlugin } = require("clean-webpack-plugin");With options interface:
import { CleanWebpackPlugin, Options } from "clean-webpack-plugin";import { CleanWebpackPlugin } from "clean-webpack-plugin";
// Basic usage - cleans webpack output directory
const webpackConfig = {
plugins: [
new CleanWebpackPlugin()
]
};
// With configuration options
const webpackConfig = {
plugins: [
new CleanWebpackPlugin({
dry: false,
verbose: true,
cleanStaleWebpackAssets: true,
protectWebpackAssets: true,
cleanOnceBeforeBuildPatterns: ['**/*'],
cleanAfterEveryBuildPatterns: ['static*.*', '!static1.js'],
dangerouslyAllowCleanPatternsOutsideProject: false
})
]
};Clean Webpack Plugin integrates with webpack's plugin system through the following components:
apply(compiler) method to register hooksdel package for pattern-based file deletionThe main plugin class that implements webpack's plugin interface.
/**
* Clean Webpack Plugin class that removes files from webpack output directory
*/
class CleanWebpackPlugin {
/**
* Creates a new Clean Webpack Plugin instance
* @param options - Configuration options for the plugin
*/
constructor(options?: Options);
/**
* Applies the plugin to a webpack compiler instance
* Required method for webpack plugin interface
* @param compiler - The webpack compiler instance
*/
apply(compiler: Compiler): void;
}
/**
* Webpack Compiler interface (from webpack package)
* This interface is provided by webpack and represents the main compiler object
*/
interface Compiler {
options: {
output?: {
path?: string;
};
};
hooks: {
emit: { tap(name: string, callback: (compilation: any) => void): void };
done: { tap(name: string, callback: (stats: any) => void): void };
};
}All configuration options for controlling plugin behavior.
interface Options {
/**
* Simulate the removal of files without actually deleting them
* When true, verbose logging is automatically enabled
* @default false
*/
dry?: boolean;
/**
* Write detailed logs to console showing what files are being removed
* Always enabled when dry is true
* @default false
*/
verbose?: boolean;
/**
* Automatically remove all unused webpack assets on rebuild
* Compares current build assets with previous build assets
* @default true
*/
cleanStaleWebpackAssets?: boolean;
/**
* Do not allow removal of current webpack assets
* Prevents accidental deletion of files webpack is actively using
* @default true
*/
protectWebpackAssets?: boolean;
/**
* File patterns to remove once prior to webpack compilation
* Not included in rebuilds (watch mode)
* Supports negative patterns with ! prefix to exclude files
* Uses del package glob patterns
* @default ['**/*']
*/
cleanOnceBeforeBuildPatterns?: string[];
/**
* File patterns to remove after every build (including watch mode)
* Used for files that are not created directly by webpack
* Supports negative patterns with ! prefix to exclude files
* Uses del package glob patterns
* @default []
*/
cleanAfterEveryBuildPatterns?: string[];
/**
* Allow clean patterns outside of process.cwd()
* Requires dry option to be explicitly set for safety
* Use with extreme caution as it can delete files outside project
* @default false
*/
dangerouslyAllowCleanPatternsOutsideProject?: boolean;
}import { CleanWebpackPlugin } from "clean-webpack-plugin";
const webpackConfig = {
plugins: [
new CleanWebpackPlugin({
dry: true,
verbose: true
})
]
};import { CleanWebpackPlugin } from "clean-webpack-plugin";
const webpackConfig = {
plugins: [
new CleanWebpackPlugin({
// Clean everything except static files before build
cleanOnceBeforeBuildPatterns: [
'**/*',
'!static-files*',
'!assets/images/**'
],
// Clean temporary files after each build
cleanAfterEveryBuildPatterns: [
'temp/**/*',
'*.log',
'!important.log'
]
})
]
};import { CleanWebpackPlugin } from "clean-webpack-plugin";
const isDevelopment = process.env.NODE_ENV === 'development';
const webpackConfig = {
plugins: [
new CleanWebpackPlugin({
// More verbose in development
verbose: isDevelopment,
// Protect assets in development for faster rebuilds
cleanStaleWebpackAssets: !isDevelopment,
// Custom patterns for development
cleanOnceBeforeBuildPatterns: isDevelopment ? [] : ['**/*']
})
]
};The plugin throws errors in the following situations:
allowExternal option// Error handling example
try {
const plugin = new CleanWebpackPlugin({
// This will throw an error
allowExternal: true
});
} catch (error) {
console.error('Plugin configuration error:', error.message);
}compiler.hooks)del package for glob pattern matching and file operations