---
url: /reference/OutputOptions.cleanDir.md
---
# cleanDir

* **Type**: `boolean`
* **Optional**

Clean output directory ([`output.dir`](./OutputOptions.dir)) before emitting output.

## Default

false

## Examples

### Basic usage

```js
export default {
  output: {
    cleanDir: true,
  },
};
```

### Multiple outputs in one config

When multiple outputs share the same directory, only set `cleanDir: true` for the first output:

```js
export default {
  output: [
    {
      dir: 'dist',
      format: 'es',
      cleanDir: true, // Clean on first output
    },
    {
      dir: 'dist',
      format: 'cjs',
      // cleanDir defaults to false, so files from first output are preserved
    },
  ],
};
```

### Multiple configurations

When multiple configurations share the same directory, only set `cleanDir: true` for the first configuration:

```js
export default [
  {
    input: 'src/index.js',
    output: {
      dir: 'dist',
      cleanDir: true, // Clean on first configuration
    },
  },
  {
    input: 'src/other.js',
    output: {
      dir: 'dist',
      // cleanDir defaults to false, so files from first config are preserved
    },
  },
];
```

### Different directories in multiple outputs

When multiple outputs use different directories, you can safely use `cleanDir: true` for each:

```js
export default {
  output: [
    {
      dir: 'dist/es',
      format: 'es',
      cleanDir: true, // Safe - different directory
    },
    {
      dir: 'dist/cjs',
      format: 'cjs',
      cleanDir: true, // Safe - different directory
    },
  ],
};
```

## In-depth

### Execution timing

The timing of the directory cleanup is important for plugin compatibility:

* The cleanup occurs **before** the `generateBundle` hook is called
* Files created by plugins during `generateBundle` or `writeBundle` hooks are **not** deleted
* This ensures that plugin-generated files are preserved even when `cleanDir` is enabled

For advanced use cases involving multiple outputs with the same `output.dir`, consider using a separate cleanup script for more control over the cleanup process.

### ⚠️ Multiple configurations behavior

When using multiple configurations or outputs, the `cleanDir` option will be executed **separately for each configuration/output** following the order they are defined.

**The two patterns:**

* **Multiple configurations**: `export default defineConfig([{ output: { cleanDir: true, ... } }, { output: {...} }])`
* **Multiple outputs in one config**: `defineConfig({ output: [{ cleanDir: true, ... }, { ... }] })`

**The problem:**

If multiple outputs share the same `output.dir` and have `cleanDir: true`, later outputs may clean files generated by earlier outputs. This happens because each output executes its cleanup independently.

**Best practice:**

To avoid this issue, only set `cleanDir: true` for the first output, or use different output directories. This ensures that all generated files are preserved.
