# Images and assets — Webpack: Module Bundling and Build Optimization

Source: https://www.skillbyai.com/en/webpack/webpack-11

> Handle images and fonts with Webpack 5 asset modules, choosing inline or emitted files by size to balance requests and caching.

## Asset handling strategies

Webpack 5 has built-in asset type handling. Use 'asset' to automatically choose between inlining small files and emitting larger files. Small images are base64 encoded inline, reducing HTTP requests. Large images are emitted as separate files for efficient caching.

## Configure asset handling

Set size thresholds for inline vs external assets.

```javascript
module.exports = {
  module: {
    rules: [
      {
        test: /\.(png|jpg|gif)$/,
        type: 'asset',
        parser: {
          dataUrlCondition: {
            maxSize: 8 * 1024 // 8KB threshold
          }
        }
      }
    ]
  }
};
```

Output:

```
Images under 8KB are base64 inlined; larger images emitted as files
```

## Image optimization matters

Use image-webpack-loader or equivalent to compress images before bundling. WebP and AVIF formats reduce size further. Lazy-load images below the fold. Responsive images using srcset provide appropriately sized images for different devices.

Quick check

**Quiz:** When should images be inlined?

- [ ] All images should always be inlined.
- [ ] Large images should be inlined for compression.
- [ ] Never, because inlining breaks the build.
- [x] When the files are small, to save extra HTTP requests.

*Answer:* When the files are small, to save extra HTTP requests.. Small files are inlined as base64 to save HTTP requests. Large files stay separate for better caching.
