An open API service indexing awesome lists of open source software.

https://github.com/humaans/next-img

A Next.js plugin for embedding optimized images.
https://github.com/humaans/next-img

javascript jpeg lighthouse-score nextjs nextjs-plugin png web webp

Last synced: about 1 month ago
JSON representation

A Next.js plugin for embedding optimized images.

Awesome Lists containing this project

README

          


next-img

Next.js plugin for embedding optimized images.



Features

- **no CDN required** — images are optimized at build time, not at runtime
- **static export** — works with `output: 'export'`, no server needed
- **import** png/jpg images with query params to control sizes and densities
- **output** to webp format with optimized fallbacks
- **resize** to multiple screen sizes and densities in a single import
- **optimize** using `sharp` at build time with results cached in your repo
- **lazy load** in modern browsers with prop forwarding (`loading="lazy"`)
- **prevent layout shift** with automatic width/height attributes
- **streamlined usage** with the built in `` component
- **art direction** with different images for different breakpoints
- **fast** builds using a persistent cache that can be checked into version control

By default **next-img** is configured to use:

- 1 breakpoint at `768px`
- 2 pixel densities of 1x, 2x
- to output the original and webp formats

All of these settings and more can be changed in your `next.config.js` or in the individual image imports.

Developed and used by [Humaans](https://humaans.io/).

## Motivation

By default Next.js or Webpack doesn't help you much with optimizing images. This means custom configuration or scripting, processing images by hand, using an image CDN or not optimising images at all. **next-img** provides and alternative streamlined approach for adding images to your Next.js projects. It combines a Next.js plugin, a custom webpack loader and a React component to make serving images in an optimal fashion in a way that is almost as easy as typing ``.

In short, it takes the following:

```js

```

Imports, resizes, optimizes, caches (persistently in the git repo) and outputs the following HTML:

```html


Jellyfish

```

[View examples](https://humaans.github.io/next-img/).

## Usage

Install the package

```
npm install next-img
```

Add the plugin to your `next.config.js`:

```js
const withImg = require('next-img/plugin')

module.exports = withImg({
nextImg: {
breakpoints: [768],
},
})
```

In your application, import the images and embed using the `` component:

```js
import { Picture } from 'next-img'
import jelly from './images/jelly.jpg?sizes=375,800'

export default () =>
```

Or inline:

```js
import { Picture } from 'next-img'

export default () =>
```

This particular example will generate the following images:

- 375px wide image to show on small screens with low pixel density of 1x
- 750px wide image to show on small screens with high pixel density of 2x or more
- 800px wide image to show on large screens with low pixel density of 1x
- 1600px wide image to show on large screens with high pixel density of 2x or more

The resized and optimized images will be saved to the `resources` directory in the root of your project during the development. This means, that if you tweak the image import parameters or plugin configuration, you might generate extra images that are no longer used by your project. In that case execute `next-img` command to remove any unnecessary images and build any missing ones:

```
npx next-img
```

Now check in the `resources` directory to your source control to be reused later for development and production builds. You can turn this feature off by setting `persistentCache: false` in the plugin configuration, in which case the images will be only stored in a temporary cache inside `.next` directory.

[View more usage examples](https://humaans.github.io/next-img/).

## Configuration

Default plugin configuration options:

```js
{
// global settings for images, can be overriden per image
breakpoints: [768],
densities: ['1x', '2x'],

// output image quality configuration
jpeg: {
quality: 80,
webp: {
quality: 90,
reductionEffort: 6,
},
},

png: {
quality: 100,
webp: {
reductionEffort: 6,
lossless: true,
},
},

// the directory within Next.js build output
imagesDir: 'images',
// the output image name template
imagesName: '[name]-[size]@[density]-[hash].[ext]',
// advanced - customise the image public path
imagesPublicPath: null,
// advanced - customise the image output path
imagesOutputPath: null,

// persistent cache allows for fast deploy and
// development workflow by avoiding reprocessing
// images that were previously processed
persistentCache: true,
persistentCacheDir: 'resources',

// this directory within .next is used in case persistent cache is turned off
cacheDir: path.join('cache', 'next-img')
}
```

Refer to [sharp documentation](https://sharp.pixelplumbing.com/api-output) for `jpeg/png/webp` compression options.

## Import Params

When importing an image, you can use query parameters to customise the optimisation:

- **sizes** - a list of comma separated sizes you will be showing images at. Note that you do not need to take into account the pixel densities here. That is, if you're showing an image at `320px` wide on your website, simply specify `320` here, the plugin will produce any necessary larger versions based on the `densities` configuration.
- **densities** - a list of comma separated densities you need each image size to be produced at. By default `1x` and `2x` sizes of images will be produced, specify `1x` if you want to produce only one image per size, or `1x,2x,3x`, etc. if you want more densities.
- **jpeg** - quality configuration options for `jpeg` images. Note, the `jpeg->webp` settings need to be nested under this param, e.g. `?jpeg[webp][quality]=95`
- **png** - quality configuration options for `png` images. Note, the `png->webp` settings need to be nested under this param, e.g. `?png[webp][lossless]=false&png[webp][nearLossless]=true`

Examples:

```js
import img1 from './images/img.jpg'
import img2 from './images/img.jpg?sizes=375,900'
import img3 from './images/img.jpg?sizes=375,900&densities=1x'
import img4 from './images/img.jpg?sizes=375,900&densities=1x,2x,3x'
import img5 from './images/img.jpg?sizes=375,900&densities=1x,2x,3x&jpeg[quality]=70&jpeg[webp][quality]=70'
```

## Picture Props

`next-img` comes with a React component making embedding images easier.

Here are the props this component access:

- **src** the imported image, or an array of imported images.
- **breakpoints** - a list of breakpoints to override the global configuration.
- **sizes** - a custom [html sizes attribute](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#How_do_you_create_responsive_images), by default the sizes attribute is generated based on the available images and breakpoints.
- **the rest of the props and ref** are forwarded to the `img` tag. This allows the use of attributes such as `alt`, `loading="lazy"`, etc..

#### A note on how sizes/media attributes are generated

When a single image is provided via the `src` prop, then each size will be configured to show up per each breakpoint available using the html [`sizes attribute`](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#How_do_you_create_responsive_images) attribute.

For example, with breakpoints `[375, 768]` and `?sizes=100,400,800` the `` component will apply the following `sizes` attribute:

```
(max-width: 375px) 100px,
(max-width: 768px) 400px,
800px
```

When an array of images is provided via the `src` prop, then each image will be configured to show up per each breakpoint available using the html [`media attribute`](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#Art_direction).

For example, with breakpoints `[375, 768]` and `src=[img1, img2, img3]` the `` component will apply the following `media` attribute:

```html




```

## Turbopack Compatibility

This plugin currently requires **webpack** and is not compatible with Turbopack. If you're using Next.js 16+ (which defaults to Turbopack), you'll need to opt into webpack mode:

```
next dev --webpack
next build --webpack
```

The core limitation is that Turbopack does not support the [`emitFile`](https://github.com/vercel/next.js/issues/78592) loader API, which next-img relies on to output processed images into the build. Until Turbopack adds support for this API, webpack mode is required.

## FAQ

**Do I have to use the `` component?**

The Picture component is optional. You can handle the imported image object however you want.

**Couldn't the images be optimized further?**

Yes, you could probably get ~10%-20% or more compression if you pass the `jpg/png` through ImageOptim or other tools. Thing is, since this plugin outputs an already well optimized webp and you'll be serving webp to most modern browsers, that removes the need to squeeze that extra file size for `jpg/png` since they are the _fallback_ images. However, there might be use cases where custom compression algorhithms are needeed and we might add support for arbitrary transformations in this plugin in the future.

## Development

```
npm install
```

You can use the docs site as the playground:

```
cd docs
npm install
npm start
```

To rebuild the persistent image cache:

```
npx next-img
```

## Ideas

- Allow turning `webp/jpg/png` output off
- Add `?raw` query support that doesn’t process the image in any way
- Inline small images as base64
- Add support for gif and webp as source images
- Translate relative sizes `?sizes=100vw,50vw,900px` to pixels based on breakpoint configuration, so image sizing can follow your design system automatically