# next/image
示例
Image 组件
版本历史| 版本 | 改变 |
| :--- | :--- |
| v12.0.0| formats configuration added.AVIF support added.Wrapper <div> changed to <span>. |
| v11.1.0| onLoadingComplete and lazyBoundary props added. |
| v11.0.0| src prop support for static import.placeholder prop added.blurDataURL prop added. |
| v10.0.5| 添加了 loader 属性。 |
| v10.0.1| 添加了 layout 属性。 |
| v10.0.0| 添加了 next/image 。 |
Note: This is API documentation for the Image Component and Image Optimization. For a feature overview and usage information for images in Next.js, please see
Images.
# 必须属性
必须为 <Image />组件设置以下属性。
# src
Must be one of the following:
- A
statically importedimage file, or - A path string. This can be either an absolute external URL, or an internal path depending on the
loaderprop orloader configuration.
如果使用的是外部 URL,则必须添将 domains 添加到 next.config.js配置文件中。
# width
图片的宽度(以像素为单位)。必须是不带单位的整数。
Required, except for statically imported images, or those with layout="fill" .
# height
图片的高度(以像素为单位)。必须是不带单位的整数。
Required, except for statically imported images, or those with layout="fill" .
# 可选参数
The <Image />component accepts a number of additional properties beyond those which are required. This section describes the most commonly-used properties of the Image component. Find details about more rarely-used properties in the Advanced Props section.
# layout
The layout behavior of the image as the viewport changes size.
| layout | Behavior | srcSet | sizes |
|---|---|---|---|
intrinsic (default) | Scale down to fit width of container, up to image size | 1x, 2x (based on imageSizes) | N/A |
fixed | Sized to width and height exactly | 1x, 2x (based on imageSizes) | N/A |
responsive | Scale to fit width of container | 640w, 750w, ... 2048w, 3840w (based on imageSizes and deviceSizes) | 100vw |
fill | Grow in both X and Y axes to fill container | 640w, 750w, ... 2048w, 3840w (based on imageSizes and deviceSizes) | 100vw |
Demo the intrinsic layout (default)When
intrinsic, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.Demo the fixed layoutWhen
fixed, the image dimensions will not change as the viewport changes (no responsiveness) similar to the nativeimgelement.Demo the responsive layoutWhen
responsive, the image will scale the dimensions down for smaller viewports and scale up for larger viewports.Ensure the parent element uses
display: blockin their stylesheet.Demo the fill layoutWhen
fill, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative.This is usually paired with the
objectFitproperty.Ensure the parent element has
position: relativein their stylesheet.Demo background image
# loader
一个用于解析 URL 的自定义函数。Setting the loader as a prop on the Image component overrides the default loader defined in the images section of next.config.js .
A loaderis a function returning a URL string for the image, given the following parameters:
srcwidthquality
Here is an example of using a custom loader with next/image:
import Image from 'next/image'
const myLoader = ({ src, width, quality }) => {
return `https://example.com/${src}?w=${width}&q=${quality || 75}`
}
const MyImage = (props) => {
return (
<Image
loader={myLoader}
src="me.png"
alt="Picture of the author"
width={500}
height={500}
/>
)
}
# sizes
A string that provides information about how wide the image will be at different breakpoints. Defaults to 100vw(the full width of the screen) when using layout="responsive"or layout="fill".
If you are using layout="fill"or layout="responsive", it's important to assign sizesfor any image that takes up less than the full viewport width.
For example, when the parent element will constrain the image to always be less than half the viewport width, use sizes="50vw". Without sizes, the image will be sent at twice the necessary resolution, decreasing performance.
If you are using layout="intrinsic"or layout="fixed", then sizesis not needed because the upper bound width is constrained already.
了解更多信息 .
# quality
图片优化后的质量,介于 1到 100之间的整数,其中 100表示最佳质量。默认值为 75。
# priority
当设置为 true 时,图片将被视为高优先级,并且会 预加载 。 Lazy loading is automatically disabled for images using priority.
You should use the priorityproperty on any image detected as the Largest Contentful Paint (LCP) element. It may be appropriate to have multiple priority images, as different images may be the LCP element for different viewport sizes.
Should only be used when the image is visible above the fold. Defaults to false.
# placeholder
A placeholder to use while the image is loading. Possible values are bluror empty. Defaults to empty.
When blur, the blurDataURL property will be used as the placeholder. If srcis an object from a static import and the imported image is .jpg, .png, .webp, or .avif, then blurDataURLwill be automatically populated.
For dynamic images, you must provide the blurDataURL](#blurdataurl) property. Solutions such as [Plaiceholder can help with base64generation.
When empty, there will be no placeholder while the image is loading, only empty space.
Try it out:
Demo the blur placeholderDemo the shimmer effect with blurDataURL propDemo the color effect with blurDataURL prop
# 高级属性
在某些情况下,你可能需要更多高级的用法。<Image />组件可以接受以下高级属性(可选)。
# objectFit
Defines how the image will fit into its parent container when using layout="fill".
This value is passed to the object-fit CSS property for the srcimage.
# objectPosition
Defines how the image is positioned within its parent element when using layout="fill".
This value is passed to the object-position CSS property applied to the image.
# onLoadingComplete
A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
The onLoadingCompletefunction accepts one parameter, an object with the following properties:
naturalWidthnaturalHeight
# loading
注意:此属性仅用于高级用途。将图片切换为
eager方式加载,通常会 损伤性能。
我们建议改用 priority 属性, 该属性几乎可以在所有的用例中迅速加载图片。
加载图片时的行为。默认为 lazy。
当设置为 lazy时,将图片的加载推迟到其距离视口(viewport)达到 某一距离时。
当设置为 eager时,图片将被立即加载。
了解更多信息
# blurDataURL
A Data URL to be used as a placeholder image before the srcimage successfully loads. Only takes effect when combined with placeholder="blur" .
Must be a base64-encoded image. It will be enlarged and blurred, so a very small image (10px or less) is recommended. Including larger images as placeholders may harm your application performance.
Try it out:
Demo the default blurDataURL propDemo the shimmer effect with blurDataURL propDemo the color effect with blurDataURL prop
You can also generate a solid color Data URL to match the image.
# lazyBoundary
A string (with similar syntax to the margin property) that acts as the bounding box used to detect the intersection of the viewport with the image and trigger lazy loading . Defaults to "200px".
Learn more
# unoptimized
当设置为 true 时,直接提供原始图片,不修改图片质量、 尺寸或格式。默认为 false。
# 其它属性
除了以下属性外,<Image />组件所接收到的其它属性将被传递给底层的 img元素:
style。使用className替代。srcSet。使用设备尺寸替代。ref. UseonLoadingCompleteinstead.decoding. 始终是"async"。
# Configuration Options
# Domains
To protect your application from malicious users, you must define a list of image provider domains that you want to be served from the Next.js Image Optimization API. This is configured in with the domainsproperty in your next.config.jsfile, as shown below:
module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
# Loader Configuration
If you want to use a cloud provider to optimize images instead of using the Next.js built-in Image Optimization API, you can configure the loaderand pathprefix in your next.config.jsfile. This allows you to use relative URLs for the Image src and automatically generate the correct absolute URL for your provider.
module.exports = {
images: {
loader: 'imgix',
path: 'https://example.com/myaccount/',
},
}
# Built-in Loaders
The following Image Optimization cloud providers are included:
- Default: Works automatically with
next dev,next start, or a custom server Vercel: Works automatically when you deploy on Vercel, no configuration necessary.Learn moreImgix:loader: 'imgix'Cloudinary:loader: 'cloudinary'Akamai:loader: 'akamai'- Custom:
loader: 'custom'use a custom cloud provider by implementing theloaderprop on thenext/imagecomponent
If you need a different provider, you can use the loader prop with next/image.
The
next/imagecomponent's default loader is not supported when usingnext export. However, other loader options will work.
The
next/imagecomponent's default loader usessquooshbecause it is quick to install and suitable for a development environment. When usingnext startin your production environment, it is strongly recommended that you installsharpby runningyarn add sharpin your project directory. This is not necessary for Vercel deployments, assharpis installed automatically.
# Advanced
The following configuration is for advanced use cases and is usually not necessary. If you choose to configure the properties below, you will override any changes to the Next.js defaults in future updates.
# Device Sizes
If you know the expected device widths of your users, you can specify a list of device width breakpoints using the deviceSizesproperty in next.config.js. These widths are used when the next/image component uses layout="responsive"or layout="fill"to ensure the correct image is served for user's device.
If no configuration is provided, the default below is used.
module.exports = {
images: {
deviceSizes: [640, 750, 828, 1080, 1200, 1920, 2048, 3840],
},
}
# Image Sizes
You can specify a list of image widths using the images.imageSizesproperty in your next.config.jsfile. These widths are concatenated with the array of device sizes](#device-sizes) to form the full array of sizes used to generate image [srcset s.
The reason there are two separate lists is that imageSizes is only used for images which provide a sizes prop, which indicates that the image is less than the full width of the screen. Therefore, the sizes in imageSizes should all be smaller than the smallest size in deviceSizes.
If no configuration is provided, the default below is used.
module.exports = {
images: {
imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
},
}
# Acceptable Formats
The default Image Optimization API will automatically detect the browser's supported image formats via the request's Acceptheader.
If the Accepthead matches more than one of the configured formats, the first match in the array is used. Therefore, the array order matters. If there is no match, the Image Optimization API will fallback to the original image's format.
If no configuration is provided, the default below is used.
module.exports = {
images: {
formats: ['image/webp'],
},
}
You can enable AVIF support with the following configuration.
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
},
}
Note: AVIF generally takes 20% longer to encode but it compresses 20% smaller compared to WebP. This means that the first time an image is requested, it will typically be slower and then subsequent requests that are cached will be faster.
# Caching Behavior
The following describes the caching algorithm for the default loader . For all other loaders, please refer to your cloud provider's documentation.
Images are optimized dynamically upon request and stored in the <distDir>/cache/imagesdirectory. The optimized image file will be served for subsequent requests until the expiration is reached. When a request is made that matches a cached but expired file, the cached file is deleted before generating a new optimized image and caching the new file.
The expiration (or rather Max Age) is defined by either the minimumCacheTTL configuration or the upstream server's Cache-Controlheader, whichever is larger. Specifically, the max-agevalue of the Cache-Controlheader is used. If both s-maxageand max-ageare found, then s-maxageis preferred.
- You can configure
minimumCacheTTLto increase the cache duration when the upstream image does not includeCache-Controlheader or the value is very low. - You can configure
deviceSizesandimageSizesto reduce the total number of possible generated images. - You can configure
formatsto disable multiple formats in favor of a single image format.
# Minimum Cache TTL
You can configure the Time to Live (TTL) in seconds for cached optimized images. In many cases, it's better to use a Static Image Import which will automatically hash the file contents and cache the image forever with a Cache-Controlheader of immutable.
module.exports = {
images: {
minimumCacheTTL: 60,
},
}
If you need to add a Cache-Controlheader for the browser (not recommended), you can configure headers on the upstream image e.g. /some-asset.jpgnot /_next/imageitself.
# Disable Static Imports
The default behavior allows you to import static files such as import icon from './icon.pngand then pass that to the srcproperty.
In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
You can disable static image imports inside your next.config.js:
module.exports = {
images: {
disableStaticImages: true,
},
}
# Related
For an overview of the Image component features and usage guidelines, see:
ImagesLearn how to display and optimize images with the Image component.
← next/link next/script →