esbuild Clean Plugin

2.0.0 · active · verified Tue Apr 21

esbuild-clean-plugin is a utility designed to integrate with esbuild's build process to automatically clean the designated output directory. It's currently stable at version 2.0.0, indicating a mature and maintained state. While a specific release cadence isn't explicitly stated, plugins often follow a release cycle aligned with their host bundler or address specific feature/bug updates as needed. Its primary differentiator lies in its deep integration as an esbuild plugin, leveraging esbuild's internal context to precisely identify and clean generated files. It offers crucial options like `initialCleanPatterns` to clear the directory before a new build, `dry` run mode for testing, and `verbose` output to track deleted files, providing fine-grained control over the build folder lifecycle directly within the esbuild configuration. This makes it a robust solution for ensuring a clean build environment without external scripts.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up `esbuild-clean-plugin` within an esbuild context, showcasing how to configure it for initial directory cleaning and verbose output.

import * as esbuild from 'esbuild';
import { cleanPlugin } from 'esbuild-clean-plugin';
import path from 'path';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

async function build() {
  // Ensure a 'dist' directory exists or will be created by esbuild
  // For demonstration, let's create a dummy entry file.
  // In a real scenario, this would be your actual source code.
  const entryPoint = path.resolve(__dirname, 'index.js');
  await esbuild.build({
    entryPoints: [entryPoint],
    bundle: true,
    outfile: path.resolve(__dirname, 'dist', 'bundle.js')
  });

  const context = await esbuild.context({
    bundle: true,
    entryPoints: [path.resolve(__dirname, 'index.js')],
    metafile: true, // Required for the plugin to work
    outdir: path.resolve(__dirname, 'dist'), // Required for the plugin to work
    plugins: [cleanPlugin({
      // Optional: Clean all files initially before the build starts
      initialCleanPatterns: ['**/*', '!package.json'],
      verbose: true // See what gets deleted
    })],
  });

  // In a typical setup, you might watch or build once
  // For this quickstart, we'll just perform an initial build with the plugin.
  await context.rebuild();
  console.log('Build complete and output directory cleaned.');

  // To stop the watch context if it were started:
  // await context.dispose();
}

// Create a dummy index.js for the quickstart to run
import { promises as fs } from 'fs';
await fs.writeFile(path.resolve(path.dirname(fileURLToPath(import.meta.url)), 'index.js'), 'console.log("Hello from esbuild!");');

build().catch(console.error);

view raw JSON →