A Next.js plugin for embedding optimized images.
Features
sharp
loading="lazy"
)<Picture />
componentBy default next-img is configured to use:
768px
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.
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 <img src='foo.png' />
.
In short, it takes the following:
<Picture src={require('./images/jelly.jpg?sizes=375,800')} alt='Jellyfish' />
Imports, resizes, optimizes, caches (persistently in the git repo) and outputs the following HTML:
<picture>
<source
type="image/webp"
srcset="
/_next/static/images/[email protected] 375w,
/_next/static/images/[email protected] 750w,
/_next/static/images/[email protected] 800w,
/_next/static/images/[email protected] 1600w
"
sizes="(max-width: 768px) 375px, 800px"
/>
<source
type="image/jpeg"
srcset="
/_next/static/images/[email protected] 375w,
/_next/static/images/[email protected] 750w,
/_next/static/images/[email protected] 800w,
/_next/static/images/[email protected] 1600w
"
sizes="(max-width: 768px) 375px, 800px"
/>
<img
src="/_next/static/images/[email protected]"
srcset="
/_next/static/images/[email protected] 375w,
/_next/static/images/[email protected] 750w,
/_next/static/images/[email protected] 800w,
/_next/static/images/[email protected] 1600w
"
width="375"
height="250"
alt="Jellyfish"
/>
</picture>
Install the package
npm install next-img
Add the plugin to your next.config.js
:
const withImg = require('next-img/plugin')
module.exports = withImg({
nextImg: {
breakpoints: [768],
},
})
In your application, import the images and embed using the <Picture />
component:
import { Picture } from 'next-img'
import jelly from './images/jelly.jpg?sizes=375,800'
export default () => <Picture src={jelly} />
Or inline:
import { Picture } from 'next-img'
export default () => <Picture src={require('./images/jelly.jpg?sizes=375,800')} />
This particular example will generate the following images:
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.
Default plugin configuration options:
{
// 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 for jpeg/png/webp
compression options.
When importing an image, you can use query parameters to customise the optimisation:
320px
wide on your website, simply specify 320
here, the plugin will produce any necessary larger versions based on the densities
configuration.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
images. Note, the jpeg->webp
settings need to be nested under this param, e.g. ?jpeg[webp][quality]=95
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:
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'
next-img
comes with a React component making embedding images easier.
Here are the props this component access:
img
tag. This allows the use of attributes such as alt
, loading="lazy"
, etc..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
attribute.
For example, with breakpoints [375, 768]
and ?sizes=100,400,800
the <Picture>
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
.
For example, with breakpoints [375, 768]
and src=[img1, img2, img3]
the <Picture>
component will apply the following media
attribute:
<picture>
<source media="(max-width: 480px)" sizes="{{img1 width}}" />
<source media="(max-width: 768px)" sizes="{{img2 width}}" />
<source sizes="{{img3 width}}" />
<img ... />
</picture>
Do I have to use the <Picture />
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.
To develop this project, you'll need to run a watcher for the <Picture />
component:
npm install
npm run watch
You can use example as the playground:
cd example
npm install
next
To execute the next-img
command in the example dir:
node ../bin/next-img
Roadmap
jpg->webp
and png->webp
conversionswebp/jpg/png
output off?raw
query support that doesn’t process the image in any waynext-img
command by plugging directly into next build
And some ideas for where this project could be taken in the future:
imagemin
optimisation plugins into the pipeline via config. This way users can control how to optimise their images more granuarly.?sizes=100vw,50vw,900px
to pixels based on the breakpoint configuration, this would allow dynamic kind of imports that depend on your design system and relative sizing of images, e.g. if css says "50vw", you will not need to do that calculation manually.require()
them.