Skip to Content
vitus·labs
Tools Next.js Images

API Reference

Complete API reference for @vitus-labs/tools-nextjs-images.

withOptimizedImages()

withOptimizedImages(config?: Partial<OptimizedImagesConfig>):
  (nextConfig?: NextConfig, nextComposePlugins?: { phase?: string }) =>
    NextConfig & { webpack: (config, options) => Configuration }

Curried factory function. First call configures image optimization, second call wraps Next.js config.

// One-step
export default withOptimizedImages({ mozjpeg: { quality: 80 } })()

// Two-step
const withImages = withOptimizedImages({ optimizeImages: true })
export default withImages({ reactStrictMode: true })

Webpack Integration

The returned config includes a webpack function that:

  1. Throws if Next.js doesn't pass defaultLoaders (Next.js < 5)
  2. Detects installed optimizer packages (memoized per project root)
  3. Detects build phase (production, export, development)
  4. Prints a warning on the server compilation if optimizeImages is on but no optimizer is installed
  5. Excludes image types from Next.js' built-in CSS-issued static/media/ image rule
  6. Registers responsive/img/webp/file loaders for each handled image format
  7. Adds resource query handlers (?webp, ?lqip, ?sprite, etc.)
  8. Chains with user's existing webpack function if present

Creating the config while process.env.TURBOPACK is set prints a one-time warning — Turbopack never calls this webpack function, so run Next with --webpack.

NextConfig

interface NextConfig {
  assetPrefix?: string
  /** Directory optimizer packages are resolved from (defaults to process.cwd()) */
  overwriteImageLoaderPaths?: string
  webpack?: (config: Configuration, options: WebpackOptions) => Configuration
  [key: string]: unknown
}

OptimizedImagesConfig

interface OptimizedImagesConfig {
  optimizeImages: boolean
  optimizeImagesInDev: boolean
  handleImages: string[]
  imagesFolder: string
  imagesName: string
  imagesPublicPath?: string
  imagesOutputPath?: string
  removeOriginalExtension: boolean
  inlineImageLimit: number
  defaultImageLoader: string

  // Optimizer options
  mozjpeg: Record<string, unknown>
  optipng: Record<string, unknown>
  pngquant: Record<string, unknown>
  gifsicle: Record<string, unknown>
  svgo: Record<string, unknown>
  svgSpriteLoader: Record<string, unknown>
  webp: Record<string, unknown>
  responsive?: Record<string, unknown> & { adapter?: unknown }
  lqip?: Record<string, unknown>
  imageTrace?: Record<string, unknown>
  [key: string]: unknown
}

Defaults

{
  optimizeImages: true,
  optimizeImagesInDev: false,
  handleImages: ['jpeg', 'png', 'svg', 'webp', 'gif'],
  imagesFolder: 'images',
  imagesName: '[name]-[hash].[ext]',
  removeOriginalExtension: false,
  inlineImageLimit: 8192,
  defaultImageLoader: 'img-loader',
  mozjpeg: {},
  optipng: {},
  pngquant: {},
  gifsicle: { interlaced: true, optimizationLevel: 3 },
  svgo: { plugins: [{ name: 'removeViewBox', active: false }] },
  svgSpriteLoader: { symbolId: '[name]-[hash:8]' },
  webp: {},
}

DetectedLoaders

interface DetectedLoaders {
  jpeg: string | false
  gif: string | false
  svg: string | false
  svgSprite: string | false
  webp: string | false
  png: string | false
  lqip: string | false
  responsive: string | false
  responsiveAdapter: string | false
}

Detection resolves each package the way the project would (createRequire rooted at overwriteImageLoaderPaths or process.cwd()), which works with isolated installs (pnpm/bun), and falls back to this package's own resolution. Results are memoized per root. PNG prefers imagemin-optipng, falls back to imagemin-pngquant. Responsive adapter prefers sharp, falls back to jimp.

Resource Query Handlers

Each query becomes a resourceQuery rule inside every handled file type's oneOf. Queries are matched on parameter boundaries ([?&]name followed by &, =, [, %5B or the end), so ?webp does not match ?webpage. Queries marked optimize: true get the active optimizer loader (img-loader or webp-loader) appended. ?url, ?inline, ?include and ?trace also have a &original combination (either order) that skips optimization. The package's own loaders (url-loader, file-loader, raw-loader, img-loader) are resolved to absolute paths so they work with isolated installs.

?url

{ test: 'url', loaders: ['file-loader'], optimize: true }

Forces file URL output regardless of inlineImageLimit.

?inline

{ test: 'inline', loaders: ['url-loader'], optimize: true }

Forces data URI inlining regardless of file size.

?include

{ test: 'include', loaders: ['raw-loader'], optimize: true }

Returns raw file contents as a string.

?original

{ test: 'original', loaders: ['url-loader'], optimize: false }

Skips all optimization — returns file as-is.

?lqip

{ test: 'lqip', loaders: ['lqip-export-loader', 'lqip-loader', 'url-loader'], optimize: false }

The default export is preSrc (a tiny base64 placeholder), with lqip-loader's output properties (src, preSrc, …) attached. The lqip options are merged into lqip-loader's options.

?lqip-colors

{ test: 'lqip-colors', loaders: ['lqip-export-loader', 'lqip-loader', 'url-loader'], optimize: false }

The default export is the extracted palette (lqip-loader runs with { base64: false, palette: true }).

?trace

{ test: 'trace', loaders: ['image-trace-loader', 'url-loader'], optimize: true }

Generates an SVG trace outline via image-trace-loader (options from imageTrace).

?webp

{ resourceQuery: 'webp', use: ['url-loader' /* mimetype image/webp */, 'webp-loader'] }

Converts an image to WebP. Registered on the JPEG/PNG/SVG/GIF rule only when 'webp' is in handleImages. The output name gets a .webp suffix ([ext].webp, or webp when removeOriginalExtension is true).

?sprite

{ resourceQuery: 'sprite', use: ['svg-sprite-loader', /* + img-loader when imagemin-svgo is installed and optimizing */] }

Generates an SVG sprite symbol exported as a React component (custom runtime generator). Only registered when svg-sprite-loader is installed; svgSpriteLoader options are forwarded.

?resize / ?size / ?sizes[]

{ test: '(?:resize|sizes?)', loaders: ['responsive-loader'], optimize: false }

Generates multiple image sizes for responsive <img srcset> (e.g. ?resize&sizes[]=300&sizes[]=600). Output name defaults to [name]-[width]-[hash].[ext]; the responsive options are merged in, and the adapter is auto-detected (sharp) when not set.

Output Path Logic

publicPath: imagesPublicPath
         ?? `${assetPrefix}/_next/static/${imagesFolder}/`   // when assetPrefix is set
         ?? `/_next/static/${imagesFolder}/`
outputPath: imagesOutputPath
         ?? `static/${imagesFolder}/`      // client bundles
         ?? `../static/${imagesFolder}/`   // server bundles

The assetPrefix is read from the Next.js config (a trailing / is handled). url-loader uses the same paths with limit: inlineImageLimit and file-loader as the fallback.

Exports

import withOptimizedImages from '@vitus-labs/tools-nextjs-images'

import type {
  DetectedLoaders,
  NextConfig,
  OptimizedImagesConfig,
} from '@vitus-labs/tools-nextjs-images'
Edit on GitHub

Last updated on

On this page