Clean Webpack Plugin
clean-webpack-plugin is a utility designed to clean or remove build folders before or after webpack compilations. Its current stable version is 4.0.0, which supports Node.js 14+ and webpack 5+. The plugin typically sees major version updates to align with breaking changes in Node.js and webpack, ensuring compatibility with the latest ecosystem features. Key differentiators include its simplicity, with no configuration needed for standard usage (cleaning webpack's output.path directory), and its intelligent handling of webpack's watch mode where it only removes assets generated by webpack that are no longer in use. It leverages the 'del' package for robust globbing support, allowing for flexible pattern matching to define what should be cleaned. It is a fundamental tool for maintaining clean build directories in webpack projects.
Common errors
-
TypeError: CleanWebpackPlugin is not a constructor
cause Attempting to instantiate the plugin without destructuring the named export, often seen with `new CleanWebpackPlugin()` after upgrading to v3+.fixCorrect the import/require statement to use destructuring: `import { CleanWebpackPlugin } from 'clean-webpack-plugin';` or `const { CleanWebpackPlugin } = require('clean-webpack-plugin');` -
Error: Cannot find module 'clean-webpack-plugin'
cause Typically indicates that the package is not installed or there's a problem with module resolution in the environment, possibly due to unsupported Node.js or webpack versions.fixEnsure the package is installed (`npm install --save-dev clean-webpack-plugin`) and that your Node.js and webpack versions meet the plugin's requirements (Node.js 10+ and webpack 4+ for v4.0.0). -
Files are not being cleaned or incorrect files are removed from my build directory.
cause Incorrect configuration of `cleanOnceBeforeBuildPatterns` or misunderstanding its default behavior relative to `output.path` and watch mode.fixFirst, test with `dry: true` and `verbose: true` in the plugin options to log actions without actual file deletion. Review `cleanOnceBeforeBuildPatterns` to ensure glob patterns are correct and paths are absolute if outside `output.path`. Remember that by default, it cleans `output.path` before build and stale webpack assets during rebuilds.
Warnings
- breaking Version 4.0.0 dropped support for Node.js 8 and webpack 3. Ensure your environment meets the new requirements (Node.js 10+, webpack 4+).
- breaking Version 3.0.0 changed the export from a default export to a named export `CleanWebpackPlugin`. Direct import without destructuring will fail.
- breaking Version 3.0.0 dropped support for Node.js 6 and webpack 2. Projects using these older versions must remain on clean-webpack-plugin v2.x.
- breaking In v3.0.0, the `cleanOnceBeforeBuildPatterns` option now uses webpack's `emit` hook instead of `compile`. This might slightly alter the timing of the cleanup process.
- gotcha The `cleanOnceBeforeBuildPatterns` option specifies patterns relative to webpack's `output.path` directory. For paths outside `output.path`, full absolute paths must be provided (e.g., `path.join(process.cwd(), 'build/**/*')`).
Install
-
npm install clean-webpack-plugin -
yarn add clean-webpack-plugin -
pnpm add clean-webpack-plugin
Imports
- CleanWebpackPlugin
import CleanWebpackPlugin from 'clean-webpack-plugin';
import { CleanWebpackPlugin } from 'clean-webpack-plugin'; - CleanWebpackPlugin
const CleanWebpackPlugin = require('clean-webpack-plugin');const { CleanWebpackPlugin } = require('clean-webpack-plugin');
Quickstart
import webpack from 'webpack';
import path from 'path';
import { CleanWebpackPlugin } from 'clean-webpack-plugin';
const webpackConfig: webpack.Configuration = {
mode: 'development', // or 'production'
entry: './src/index.ts',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
// To demonstrate clean-webpack-plugin, disable Webpack 5's built-in clean
clean: false,
},
resolve: {
extensions: ['.ts', '.js'],
},
module: {
rules: [
{
test: /\.ts$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
plugins: [
/**
* The CleanWebpackPlugin will remove all files inside webpack's output.path directory
* (e.g., `<PROJECT_DIR>/dist/`) once before the initial build. During rebuilds in watch mode,
* it intelligently removes only the webpack assets that are no longer in use. This example
* uses default options, which is often sufficient for most projects.
*/
new CleanWebpackPlugin(),
],
};
// To use this configuration with the webpack CLI, save it as webpack.config.ts
// or webpack.config.js and run 'webpack' or 'webpack serve'.
// Alternatively, it can be consumed programmatically:
// const compiler = webpack(webpackConfig);
// compiler.run((err, stats) => {
// if (err) { console.error(err); return; }
// console.log(stats?.toString({ colors: true }));
// });
export default webpackConfig;