# How to Use the export-images.config.js Configuration File in next-export-optimize-images

> Learn how to configure your image exports with the `export-images.config.js` file in next-export-optimize-images. Optimize your build process and image assets efficiently.

- Repository: [d-suke/next-export-optimize-images](https://github.com/dc7290/next-export-optimize-images)
- Tags: how-to-guide
- Published: 2026-02-28

---

**`next-export-optimize-images` reads an [`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js) (or `.cjs`) file from your project root, validates it against the internal `Config` type, and serializes a copy into `node_modules` for the Webpack loader to consume at build-time.**

The `dc7290/next-export-optimize-images` library optimizes images during Next.js static generation. To customize output directories, image quality, format conversion, and remote asset handling, you create an **[`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js)** configuration file. The library discovers this file during the build process, serializes its contents (including any functions), and makes it available to the optimization loader at runtime.

## Configuration File Discovery and Loading Process

The library implements a five-stage pipeline to consume your configuration, implemented primarily in [`src/withExportImages.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/withExportImages.ts) and [`src/utils/getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/utils/getConfig.ts).

**File Discovery and Import**
In [`src/withExportImages.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/withExportImages.ts), the plugin checks `process.cwd()` for [`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js) or `export-images.config.cjs`. If found, it requires the file using `require(resolvedConfigPath)` and stores the raw object. If `remoteImages` is defined as an async function, the library awaits its resolution before proceeding.

**Serialization to Node Modules**
The validated configuration is written as a JSON-serialized file (with functions converted to strings) to [`node_modules/next-export-optimize-images/export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/node_modules/next-export-optimize-images/export-images.config.js). This allows the Webpack loader to access the configuration without traversing the filesystem during the build.

**Runtime Reconstruction**
When the loader executes, [`src/utils/getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/utils/getConfig.ts) imports the generated file and reconstructs any stringified functions using the `Function` constructor. This restores `filenameGenerator` and `sourceImageParser` as executable code, exposing a fully typed `Config` object to the rest of the library.

## Configuration Schema and Available Options

Your [`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js) must export an object conforming to the `Config` interface defined in [`src/utils/getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/utils/getConfig.ts). All fields are optional; the library applies defaults when values are omitted.

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `outDir` | `string` | `'out'` | Directory passed to `next export -o …`. |
| `imageDir` | `string` | `'_next/static/chunks/images'` | Output directory for optimized images. |
| `cacheDir` | `string` | `'node_modules/.cache'` | Filesystem cache location for processed images. |
| `ignorePaths` | `string[]` | `[]` | Relative paths (from `public/`) to exclude from optimization. |
| `basePath` | `string` | `''` | Must match `basePath` in [`next.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/next.config.js) if used. |
| `externalImageDir` | `string` | `'_next/static/media'` | Output folder for downloaded external images. |
| `quality` | `number` | `75` | JPEG/WEBP/AVIF quality factor (0-100). |
| `filenameGenerator` | `(props) => string` | – | Custom logic to build output filenames. |
| `sourceImageParser` | `(args) => ParsedImageInfo` | – | Override how the library extracts path, name, and extension from source URLs. |
| `sharpOptions` | `{ png?, jpg?, webp?, avif? }` | – | Direct Sharp output options (e.g., `effort`, `compressionLevel`). |
| `convertFormat` | `[AllowedFormat, AllowedFormat][]` | – | Convert source formats to alternatives (e.g., `['png', 'webp']`). |
| `generateFormats` | `('webp' \| 'avif')[]` | `['webp']` | Extra image formats generated for the `<Picture>` component. |
| `remoteImages` | `string[] \| () => string[] \| Promise<string[]>` | – | URLs of external images to download and optimize. |
| `remoteImagesDownloadsDelay` | `number` | – | Milliseconds to wait between remote image downloads (rate-limiting). |
| `processingConcurrency` | `number` | `10` | Number of images processed in parallel. |
| `mode` | `'build' \| 'export'` | `'export'` | `"build"` uses `next build` + `next start`; `"export"` uses `next export`. |

## Runtime Processing of Configuration Values

After serialization, [`getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/getConfig.ts) handles the reconstruction of function-based options. The library uses the following pattern to restore executable logic:

```typescript
filenameGenerator: config.filenameGenerator
  ? Function(`"use strict";return (${config.filenameGenerator})`)()
  : undefined,
sourceImageParser: config.sourceImageParser
  ? Function(`"use strict";return (${config.sourceImageParser})`)()
  : undefined,

```

This ensures that custom filename generators and source parsers execute as native JavaScript functions within the loader context, despite being transmitted as strings through the serialization process.

## Practical Configuration Examples

### 1. Minimal Configuration

Create a file at the project root to accept all defaults:

```js
// export-images.config.js
/** @type {import('next-export-optimize-images').Config} */
module.exports = {
  // No options required – defaults are applied automatically.
};

```

### 2. Custom Output Directories and Quality

Redirect optimized assets and increase image quality:

```js
// export-images.config.js
module.exports = {
  outDir: 'out-static',
  imageDir: '_optimized',
  quality: 80,
};

```

### 3. Custom Filename Generation

Define a deterministic filename pattern that includes dimensions:

```js
// export-images.config.js
module.exports = {
  /**
   * Build a filename that includes path, name, width and extension.
   * Example: images-gallery-photo-800.webp
   */
  filenameGenerator: ({ path, name, width, extension }) =>
    `${path.replace(/^\//, '').replace(/\//g, '-')}-${name}.${width}.${extension}`,
};

```

### 4. Non-Standard Source URL Parsing

Handle query-string-based image sources:

```js
// export-images.config.js
module.exports = {
  sourceImageParser: ({ src, defaultParser }) => {
    const match = src.match(/^.*\?fileId=(.*)&extension=(\w+).*$/);
    if (!match) return defaultParser(src);
    return {
      pathWithoutName: '',
      name: match[1],
      extension: match[2],
    };
  },
};

```

### 5. Sharp Options and Format Conversion

Control encoder settings and convert formats automatically:

```js
// export-images.config.js
module.exports = {
  sharpOptions: {
    png: { effort: 1 },
    webp: { quality: 80, effort: 0 },
  },
  convertFormat: [
    ['png', 'webp'],
    ['jpg', 'avif'],
  ],
};

```

### 6. Remote Images with Rate Limiting

Download external assets with a delay between requests:

```js
// export-images.config.js
module.exports = {
  remoteImages: [
    'https://cdn.example.com/banner.jpg',
    'https://cdn.example.com/logo.png',
  ],
  remoteImagesDownloadsDelay: 200, // 200ms between each download
};

```

### 7. Build Mode for SSR

Enable optimization with `next build` instead of static export:

```js
// export-images.config.js
module.exports = {
  mode: 'build', // Enables use with `next build` + `next start`
};

```

## Summary

- Place **[`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js)** (or `.cjs`) in your project root; the library discovers it via `process.cwd()`.
- All configuration fields are optional; the library provides sensible defaults for output paths, quality, and concurrency.
- Functions defined in the configuration (`filenameGenerator`, `sourceImageParser`) are serialized as strings and reconstructed at runtime using the `Function` constructor.
- The configuration controls optimization parameters, format conversion, remote image downloading, and build mode (`build` vs `export`).
- Source files [`src/withExportImages.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/withExportImages.ts) and [`src/utils/getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/utils/getConfig.ts) implement the full lifecycle: discovery, validation, serialization, and runtime consumption.

## Frequently Asked Questions

### Where should I place the export-images.config.js file?

The library searches for [`export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/export-images.config.js) or `export-images.config.cjs` in the current working directory (`process.cwd()`), which is typically your project root where [`package.json`](https://github.com/dc7290/next-export-optimize-images/blob/main/package.json) resides. Place the file there; the `withExportImages` function in [`src/withExportImages.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/withExportImages.ts) handles the discovery automatically.

### Can I use TypeScript or ESM for the configuration file?

Currently, the library only supports JavaScript (`.js`) or CommonJS (`.cjs`) configuration files. The `withExportImages` implementation uses `require()` to import the configuration, which necessitates CommonJS format. TypeScript definitions are available via JSDoc annotations (`@type {import('next-export-optimize-images').Config}`) for type checking in supported editors.

### How does the library handle functions in the configuration?

Functions like `filenameGenerator` and `sourceImageParser` are serialized to strings using `toString()` during the build phase and written to [`node_modules/next-export-optimize-images/export-images.config.js`](https://github.com/dc7290/next-export-optimize-images/blob/main/node_modules/next-export-optimize-images/export-images.config.js). At runtime, [`src/utils/getConfig.ts`](https://github.com/dc7290/next-export-optimize-images/blob/main/src/utils/getConfig.ts) reconstructs them using `Function('"use strict";return (' + fnString + ')')()`, converting them back into executable JavaScript functions for the Webpack loader.

### What is the difference between `mode: 'build'` and `mode: 'export'`?

`mode: 'export'` (the default) optimizes images during `next export` for static site generation, emitting assets to the `outDir`. `mode: 'build'` enables the optimization pipeline for dynamic Next.js applications using `next build` and `next start`, allowing image optimization in server-side rendered environments without static export.