or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Clean Webpack Plugin

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.

Package Information

  • Package Name: clean-webpack-plugin
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install --save-dev clean-webpack-plugin

Core Imports

import { CleanWebpackPlugin } from "clean-webpack-plugin";

For CommonJS:

const { CleanWebpackPlugin } = require("clean-webpack-plugin");

With options interface:

import { CleanWebpackPlugin, Options } from "clean-webpack-plugin";

Basic Usage

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
    })
  ]
};

Architecture

Clean Webpack Plugin integrates with webpack's plugin system through the following components:

  • Constructor: Validates and normalizes configuration options
  • Plugin Interface: Implements webpack's apply(compiler) method to register hooks
  • Lifecycle Integration: Hooks into webpack's emit and done phases for file cleaning
  • File Operations: Uses the del package for pattern-based file deletion
  • Safety Features: Includes protection mechanisms and validation for safe operation

Capabilities

Plugin Class

The 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 };
  };
}

Configuration Options

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;
}

Usage Examples

Dry Run Mode

import { CleanWebpackPlugin } from "clean-webpack-plugin";

const webpackConfig = {
  plugins: [
    new CleanWebpackPlugin({
      dry: true,
      verbose: true
    })
  ]
};

Custom Clean Patterns

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'
      ]
    })
  ]
};

Development vs Production Configuration

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 ? [] : ['**/*']
    })
  ]
};

Error Handling

The plugin throws errors in the following situations:

  • Invalid options: When constructor receives non-plain object
  • Deprecated options: When using removed allowExternal option
  • Unsafe patterns: When trying to clean outside project without proper configuration
  • Missing webpack config: When webpack output.path is not defined
// Error handling example
try {
  const plugin = new CleanWebpackPlugin({
    // This will throw an error
    allowExternal: true
  });
} catch (error) {
  console.error('Plugin configuration error:', error.message);
}

Integration Notes

  • Webpack Compatibility: Supports webpack 4.x and 5.x
  • Hook Registration: Uses webpack's modern hook system (compiler.hooks)
  • Asset Protection: Automatically protects current webpack assets from deletion
  • Pattern Matching: Uses del package for glob pattern matching and file operations
  • Context Awareness: All file operations are performed relative to webpack's output directory