CleanPlugin
TheCleanPlugin removes/cleans the output directory (typically dist) before each build, ensuring that only files generated by the current build are present.
In webpack 5, this functionality is built into the core through the
output.clean option. The plugin is still available for advanced use cases.Basic Usage
Simple approach (webpack 5+):Configuration Options
Enable cleaning of the output directory.When set to
true, removes all files in the output directory before emit.Log what would be removed instead of actually removing it (dry run).
Keep specific files/directories that match the pattern.
Advanced Usage
Keep Specific Files
Keep certain files while cleaning others:Keep Pattern
Use glob patterns to specify files to keep:Dry Run
Test what would be deleted without actually deleting:How It Works
The CleanPlugin:- Runs before webpack emits files to the output directory
- Reads the current contents of the output directory
- Compares with the list of assets webpack will emit
- Removes files/directories not in the current build
- Respects the
keepoption to preserve specified files
Use Cases
Remove Old Build Artifacts
Automatically clean up old bundles when filenames include hashes:Preserve Static Assets
Keep manually added files in the output directory:Multi-Compiler Setup
When using multiple webpack configs with the same output:Migration from webpack 4
In webpack 4, you typically usedclean-webpack-plugin. In webpack 5, use the built-in option:
Before (webpack 4):
Related
- Output Configuration - Output directory and file options
- Production Guide - Production build best practices
- Caching Guide - Cache busting with content hashes