Clean Webpack Plugin

4.0.0 · active · verified Tue Apr 21

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

Warnings

Install

Imports

Quickstart

This configuration demonstrates the basic setup for `clean-webpack-plugin` in a webpack project. It initializes the plugin with its default settings, which automatically cleans the output directory before the initial build and manages stale assets during subsequent rebuilds, ensuring a clean build folder for a TypeScript project.

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;

view raw JSON →