图片(旧版)
Examples
从 Next.js 13 开始,next/image
组件被重写,以提高性能和开发者体验。为了提供向后兼容的升级方案,旧的 next/image
更名为 next/legacy/image
。
¥Starting with Next.js 13, the next/image
component was rewritten to improve both the performance and developer experience. In order to provide a backwards compatible upgrade solution, the old next/image
was renamed to next/legacy/image
.
查看新款 next/image
API 参考
¥View the new next/image
API Reference
比较
¥Comparison
与 next/legacy/image
相比,新的 next/image
组件有以下变化:
¥Compared to next/legacy/image
, the new next/image
component has the following changes:
-
删除
<img>
周围的<span>
封装以支持 原生计算纵横比¥Removes
<span>
wrapper around<img>
in favor of native computed aspect ratio -
添加对规范
style
属性的支持¥Adds support for canonical
style
prop-
删除
layout
属性以支持style
或className
¥Removes
layout
prop in favor ofstyle
orclassName
-
删除
objectFit
属性以支持style
或className
¥Removes
objectFit
prop in favor ofstyle
orclassName
-
删除
objectPosition
属性以支持style
或className
¥Removes
objectPosition
prop in favor ofstyle
orclassName
-
-
删除
IntersectionObserver
实现以支持 原生延迟加载¥Removes
IntersectionObserver
implementation in favor of native lazy loading-
删除
lazyBoundary
属性,因为没有原生等效项¥Removes
lazyBoundary
prop since there is no native equivalent -
删除
lazyRoot
属性,因为没有原生等效项¥Removes
lazyRoot
prop since there is no native equivalent
-
-
删除
loader
配置以支持loader
属性¥Removes
loader
config in favor ofloader
prop -
将
alt
属性从可选更改为必需¥Changed
alt
prop from optional to required -
更改了
onLoadingComplete
回调以接收对<img>
元素的引用¥Changed
onLoadingComplete
callback to receive reference to<img>
element
必需属性
¥Required Props
<Image />
组件需要以下属性。
¥The <Image />
component requires the following properties.
src
必须是以下之一:
¥Must be one of the following:
-
静态导入 图片文件
¥A statically imported image file
-
路径字符串。这可以是绝对外部 URL,也可以是内部路径,具体取决于 loader 属性或 加载器配置。
¥A path string. This can be either an absolute external URL, or an internal path depending on the loader prop or loader configuration.
使用默认 loader 时,还请考虑以下源图片:
¥When using the default loader, also consider the following for source images:
-
当 src 是外部 URL 时,你还必须配置 remotePatterns
¥When src is an external URL, you must also configure remotePatterns
-
当 src 为 animated 或不是已知格式(JPEG、PNG、WebP、AVIF、GIF、TIFF)时,图片将按原样提供
¥When src is animated or not a known format (JPEG, PNG, WebP, AVIF, GIF, TIFF) the image will be served as-is
-
当 src 为 SVG 格式时,除非启用
unoptimized
或dangerouslyAllowSVG
,否则它将被阻止¥When src is SVG format, it will be blocked unless
unoptimized
ordangerouslyAllowSVG
is enabled
width
width
属性可以表示渲染宽度或原始宽度(以像素为单位),具体取决于 layout
和 sizes
属性。
¥The width
property can represent either the rendered width or original width in pixels, depending on the layout
and sizes
properties.
当使用 layout="intrinsic"
或 layout="fixed"
时,width
属性表示以像素为单位的渲染宽度,因此它将影响图片显示的大小。
¥When using layout="intrinsic"
or layout="fixed"
the width
property represents the rendered width in pixels, so it will affect how large the image appears.
当使用 layout="responsive"
、layout="fill"
时,width
属性代表原始宽度(以像素为单位),因此它只会影响宽高比。
¥When using layout="responsive"
, layout="fill"
, the width
property represents the original width in pixels, so it will only affect the aspect ratio.
width
属性是必需的,静态导入的图片 或具有 layout="fill"
的属性除外。
¥The width
property is required, except for statically imported images, or those with layout="fill"
.
height
height
属性可以表示渲染高度或原始高度(以像素为单位),具体取决于 layout
和 sizes
属性。
¥The height
property can represent either the rendered height or original height in pixels, depending on the layout
and sizes
properties.
当使用 layout="intrinsic"
或 layout="fixed"
时,height
属性表示以像素为单位的渲染高度,因此它将影响图片的显示大小。
¥When using layout="intrinsic"
or layout="fixed"
the height
property represents the rendered height in pixels, so it will affect how large the image appears.
当使用 layout="responsive"
、layout="fill"
时,height
属性代表原始高度(以像素为单位),因此它只会影响宽高比。
¥When using layout="responsive"
, layout="fill"
, the height
property represents the original height in pixels, so it will only affect the aspect ratio.
height
属性是必需的,静态导入的图片 或具有 layout="fill"
的属性除外。
¥The height
property is required, except for statically imported images, or those with layout="fill"
.
可选属性
¥Optional Props
<Image />
组件接受除所需属性之外的许多附加属性。本节介绍 Image 组件最常用的属性。在 高级属性 部分中查找更多很少使用的属性的详细信息。
¥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 | 行为 | srcSet | sizes | 有封装纸和尺寸测量器 |
---|---|---|---|---|
intrinsic (默认) | 缩小以适合容器的宽度,放大至图片大小 | 1x 、2x (基于 imageSizes) | 不适用 | yes |
fixed | 尺寸精确到 width 和 height | 1x 、2x (基于 imageSizes) | 不适用 | yes |
responsive | 缩放以适合容器的宽度 | 640w 、750w 、...2048w 、3840w (基于 imageSizes 和 deviceSizes) | 100vw | yes |
fill | 在 X 和 Y 轴上增长以填充容器 | 640w 、750w 、...2048w 、3840w (基于 imageSizes 和 deviceSizes) | 100vw | yes |
-
¥Demo the
intrinsic
layout (default)-
当
intrinsic
时,图片将缩小较小视口的尺寸,但保持较大视口的原始尺寸。¥When
intrinsic
, the image will scale the dimensions down for smaller viewports, but maintain the original dimensions for larger viewports.
-
-
-
当
fixed
时,图片尺寸不会随着视口的变化而变化(无响应),类似于原生img
元素。¥When
fixed
, the image dimensions will not change as the viewport changes (no responsiveness) similar to the nativeimg
element.
-
-
-
当
responsive
时,图片将针对较小的视口缩小尺寸,并针对较大的视口放大尺寸。¥When
responsive
, the image will scale the dimensions down for smaller viewports and scale up for larger viewports. -
确保父元素在其样式表中使用
display: block
。¥Ensure the parent element uses
display: block
in their stylesheet.
-
-
-
当
fill
时,图片会将宽度和高度拉伸到父元素的尺寸,前提是父元素是相对的。¥When
fill
, the image will stretch both width and height to the dimensions of the parent element, provided the parent element is relative. -
这通常与
objectFit
属性配对。¥This is usually paired with the
objectFit
property. -
确保父元素的样式表中有
position: relative
。¥Ensure the parent element has
position: relative
in their stylesheet.
-
loader
用于解析 URL 的自定义函数。将加载程序设置为 Image 组件上的 prop 会覆盖 next.config.js
的 images
部分.xml 中定义的默认加载程序。
¥A custom function used to resolve URLs. Setting the loader as a prop on the Image component overrides the default loader defined in the images
section of next.config.js
.
loader
是一个返回图片 URL 字符串的函数,给定以下参数:
¥A loader
is a function returning a URL string for the image, given the following parameters:
这是使用自定义加载程序的示例:
¥Here is an example of using a custom loader:
import Image from 'next/legacy/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
一个字符串,提供有关图片在不同断点处的宽度的信息。sizes
的值将极大地影响使用 layout="responsive"
或 layout="fill"
的图片的性能。对于使用 layout="intrinsic"
或 layout="fixed"
的图片,它将被忽略。
¥A string that provides information about how wide the image will be at different breakpoints. The value of sizes
will greatly affect performance for images using layout="responsive"
or layout="fill"
. It will be ignored for images using layout="intrinsic"
or layout="fixed"
.
sizes
属性有两个与图片性能相关的重要目的:
¥The sizes
property serves two important purposes related to image performance:
首先,浏览器使用 sizes
的值来确定从 next/legacy/image
自动生成的源集中下载图片的大小。当浏览器选择时,它还不知道页面上图片的大小,因此它选择与视口大小相同或更大的图片。sizes
属性允许你告诉浏览器图片实际上小于全屏。如果未指定 sizes
值,则使用默认值 100vw
(全屏宽度)。
¥First, the value of sizes
is used by the browser to determine which size of the image to download, from next/legacy/image
's automatically-generated source set. When the browser chooses, it does not yet know the size of the image on the page, so it selects an image that is the same size or larger than the viewport. The sizes
property allows you to tell the browser that the image will actually be smaller than full screen. If you don't specify a sizes
value, a default value of 100vw
(full screen width) is used.
其次,解析 sizes
值并用于修剪自动创建的源集中的值。如果 sizes
属性包括诸如 50vw
之类的尺寸(代表视口宽度的百分比),则源集将被修剪以不包括任何太小而不必要的值。
¥Second, the sizes
value is parsed and used to trim the values in the automatically-created source set. If the sizes
property includes sizes such as 50vw
, which represent a percentage of the viewport width, then the source set is trimmed to not include any values which are too small to ever be necessary.
例如,如果你知道你的样式将导致图片在移动设备上为全宽、在平板电脑上为 2 列布局、在桌面显示器上为 3 列布局,则应包含尺寸属性,如下所示 :
¥For example, if you know your styling will cause an image to be full-width on mobile devices, in a 2-column layout on tablets, and a 3-column layout on desktop displays, you should include a sizes property such as the following:
import Image from 'next/legacy/image'
const Example = () => (
<div className="grid-element">
<Image
src="/example.png"
layout="fill"
sizes="(max-width: 768px) 100vw,
(max-width: 1200px) 50vw,
33vw"
/>
</div>
)
此示例 sizes
可能会对性能指标产生巨大影响。如果没有 33vw
尺寸,从服务器选择的图片宽度将是所需宽度的 3 倍。由于文件大小与宽度的平方成正比,因此如果没有 sizes
,用户将下载比所需大小大 9 倍的图片。
¥This example sizes
could have a dramatic effect on performance metrics. Without the 33vw
sizes, the image selected from the server would be 3 times as wide as it needs to be. Because file size is proportional to the square of the width, without sizes
the user would download an image that's 9 times larger than necessary.
了解有关 srcset
和 sizes
的更多信息:
¥Learn more about srcset
and sizes
:
quality
优化图片的质量,1
和 100
之间的整数,其中 100
是最佳质量。默认为 75
。
¥The quality of the optimized image, an integer between 1
and 100
where 100
is the best quality. Defaults to 75
.
priority
如果为 true,则图片将被视为高优先级和 preload。使用 priority
的图片会自动禁用延迟加载。
¥When true, the image will be considered high priority and
preload. Lazy loading is automatically disabled for images using priority
.
你应该对检测为 最大内容涂料 (LCP) 元素的任何图片使用 priority
属性。具有多个优先级图片可能是合适的,因为不同的图片可能是不同视口尺寸的 LCP 元素。
¥You should use the priority
property 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.
仅当图片在首屏上方可见时才应使用。默认为 false
。
¥Should only be used when the image is visible above the fold. Defaults to false
.
placeholder
加载图片时使用的占位符。可能的值为 blur
或 empty
。默认为 empty
。
¥A placeholder to use while the image is loading. Possible values are blur
or empty
. Defaults to empty
.
当 blur
时,blurDataURL
属性将用作占位符。如果 src
是 静态导入 中的对象,并且导入的图片是 .jpg
、.png
、.webp
或 .avif
,则将自动填充 blurDataURL
。
¥When blur
, the blurDataURL
property will be used as the placeholder. If src
is an object from a static import and the imported image is .jpg
, .png
, .webp
, or .avif
, then blurDataURL
will be automatically populated.
对于动态图片,你必须提供 blurDataURL
属性。占位符 等解决方案可以帮助生成 base64
。
¥For dynamic images, you must provide the blurDataURL
property. Solutions such as Plaiceholder can help with base64
generation.
当 empty
时,图片加载时不会有占位符,只有空白空间。
¥When empty
, there will be no placeholder while the image is loading, only empty space.
试试看:
¥Try it out:
高级属性
¥Advanced Props
在某些情况下,你可能需要更高级的用法。<Image />
组件可选择接受以下高级属性。
¥In some cases, you may need more advanced usage. The <Image />
component optionally accepts the following advanced properties.
style
允许 传递 CSS 样式 到底层图片元素。
¥Allows passing CSS styles to the underlying image element.
请注意,所有 layout
模式都会将自己的样式应用于图片元素,并且这些自动样式优先于 style
属性。
¥Note that all layout
modes apply their own styles to the image element, and these automatic styles take precedence over the style
prop.
另请记住,所需的 width
和 height
属性可以与你的样式互动。如果你使用样式修改图片的 width
,则还必须设置 height="auto"
样式,否则图片会变形。
¥Also keep in mind that the required width
and height
props can interact with your styling. If you use styling to modify an image's width
, you must set the height="auto"
style as well, or your image will be distorted.
objectFit
定义使用 layout="fill"
时图片如何适合其父容器。
¥Defines how the image will fit into its parent container when using layout="fill"
.
该值被传递到 src
图片的 对象适合 CSS 属性。
¥This value is passed to the object-fit CSS property for the src
image.
objectPosition
定义使用 layout="fill"
时图片在其父元素中的定位方式。
¥Defines how the image is positioned within its parent element when using layout="fill"
.
该值被传递到应用于图片的 对象位置 CSS 属性。
¥This value is passed to the object-position CSS property applied to the image.
onLoadingComplete
图片完全加载且 placeholder 已删除后调用的回调函数。
¥A callback function that is invoked once the image is completely loaded and the placeholder has been removed.
onLoadingComplete
函数接受一个参数,即具有以下属性的对象:
¥The onLoadingComplete
function accepts one parameter, an object with the following properties:
loading
图片的加载行为。默认为 lazy
。
¥The loading behavior of the image. Defaults to lazy
.
当 lazy
时,推迟加载图片,直到它达到距视口的计算距离。
¥When lazy
, defer loading the image until it reaches a calculated distance from
the viewport.
当 eager
时,立即加载图片。
¥When eager
, load the image immediately.
blurDataURL
在成功加载 src
图片之前,将 数据网址 用作占位符图片。仅与 placeholder="blur"
组合时生效。
¥A Data URL to
be used as a placeholder image before the src
image successfully loads. Only takes effect when combined
with placeholder="blur"
.
必须是 base64 编码的图片。它会被放大并模糊,因此建议使用非常小的图片(10px 或更小)。包含较大的图片作为占位符可能会损害你的应用性能。
¥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:
你还可以 生成纯色数据 URL 来匹配图片。
¥You can also generate a solid color Data URL to match the image.
lazyBoundary
一个字符串(与 margin 属性具有类似的语法),充当边界框,用于检测视口与图片的交集并触发惰性 loading。默认为 "200px"
。
¥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"
.
如果图片嵌套在根文档之外的可滚动父元素中,你还需要分配 lazyRoot 属性。
¥If the image is nested in a scrollable parent element other than the root document, you will also need to assign the lazyRoot prop.
lazyRoot
指向可滚动父元素的 React 引用。默认为 null
(文档视口)。
¥A React Ref pointing to the scrollable parent element. Defaults to null
(the document viewport).
Ref 必须指向一个 DOM 元素或一个 React 组件,转发参考 指向底层 DOM 元素。
¥The Ref must point to a DOM element or a React component that forwards the Ref to the underlying DOM element.
指向 DOM 元素的示例
¥Example pointing to a DOM element
import Image from 'next/legacy/image'
import React from 'react'
const Example = () => {
const lazyRoot = React.useRef(null)
return (
<div ref={lazyRoot} >
<Image lazyRoot={lazyRoot} src="/one.jpg" width="500" height="500" />
<Image lazyRoot={lazyRoot} src="/two.jpg" width="500" height="500" />
</div>
)
}
指向 React 组件的示例
¥Example pointing to a React component
import Image from 'next/legacy/image'
import React from 'react'
const Container = React.forwardRef((props, ref) => {
return (
<div ref={ref} >
{props.children}
</div>
)
})
const Example = () => {
const lazyRoot = React.useRef(null)
return (
<Container ref={lazyRoot}>
<Image lazyRoot={lazyRoot} src="/one.jpg" width="500" height="500" />
<Image lazyRoot={lazyRoot} src="/two.jpg" width="500" height="500" />
</Container>
)
}
unoptimized
如果为 true,则源图片将按原样提供,而不是更改质量、大小或格式。默认为 false
。
¥When true, the source image will be served as-is instead of changing quality,
size, or format. Defaults to false
.
import Image from 'next/image'
const UnoptimizedImage = (props) => {
return <Image {...props} unoptimized />
}
从 Next.js 12.3.0 开始,可以通过使用以下配置更新 next.config.js
来将此属性分配给所有图片:
¥Since Next.js 12.3.0, this prop can be assigned to all images by updating next.config.js
with the following configuration:
module.exports = {
images: {
unoptimized: true,
},
}
其他属性
¥Other Props
<Image />
组件上的其他属性将传递给底层 img
元素,但以下属性除外:
¥Other properties on the <Image />
component will be passed to the underlying
img
element with the exception of the following:
-
srcSet
。请改用 设备尺寸。¥
srcSet
. Use Device Sizes instead. -
ref
。请改用onLoadingComplete
。¥
ref
. UseonLoadingComplete
instead. -
decoding
。始终是"async"
。¥
decoding
. It is always"async"
.
配置选项
¥Configuration Options
远程模式
¥Remote Patterns
为了保护你的应用免受恶意用户的侵害,需要进行配置才能使用外部映像。这可确保 Next.js 图片优化 API 只能提供你账户中的外部图片。这些外部图片可以使用 next.config.js
文件中的 remotePatterns
属性进行配置,如下所示:
¥To protect your application from malicious users, configuration is required in order to use external images. This ensures that only external images from your account can be served from the Next.js Image Optimization API. These external images can be configured with the remotePatterns
property in your next.config.js
file, as shown below:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'example.com',
port: '',
pathname: '/account123/**',
search: '',
},
],
},
}
很高兴知道:上述示例将确保
next/legacy/image
的src
属性必须以https://example.com/account123/
开头,并且不能有查询字符串。任何其他协议、主机名、端口或不匹配的路径都将响应 400 Bad Request。¥Good to know: The example above will ensure the
src
property ofnext/legacy/image
must start withhttps://example.com/account123/
and must not have a query string. Any other protocol, hostname, port, or unmatched path will respond with 400 Bad Request.
下面是使用 hostname
中的通配符模式的 next.config.js
文件中的 remotePatterns
属性的示例:
¥Below is an example of the remotePatterns
property in the next.config.js
file using a wildcard pattern in the hostname
:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: '**.example.com',
port: '',
search: '',
},
],
},
}
很高兴知道:上面的示例将确保
next/legacy/image
的src
属性必须以https://img1.example.com
或https://me.avatar.example.com
或任意数量的子域开头。它不能有端口或查询字符串。任何其他协议或不匹配的主机名都将以 400 Bad Request 响应。¥Good to know: The example above will ensure the
src
property ofnext/legacy/image
must start withhttps://img1.example.com
orhttps://me.avatar.example.com
or any number of subdomains. It cannot have a port or query string. Any other protocol or unmatched hostname will respond with 400 Bad Request.
通配符模式可用于 pathname
和 hostname
,并具有以下语法:
¥Wildcard patterns can be used for both pathname
and hostname
and have the following syntax:
-
*
匹配单个路径段或子域¥
*
match a single path segment or subdomain -
**
匹配末尾任意数量的路径段或开头的子域¥
**
match any number of path segments at the end or subdomains at the beginning
**
语法在模式中间不起作用。
¥The **
syntax does not work in the middle of the pattern.
很高兴知道:省略
protocol
、port
、pathname
或search
时,则隐含通配符**
。不建议这样做,因为它可能会让恶意行为者优化你不希望的 URL。¥Good to know: When omitting
protocol
,port
,pathname
, orsearch
then the wildcard**
is implied. This is not recommended because it may allow malicious actors to optimize urls you did not intend.
下面是使用 search
的 next.config.js
文件中的 remotePatterns
属性的示例:
¥Below is an example of the remotePatterns
property in the next.config.js
file using search
:
module.exports = {
images: {
remotePatterns: [
{
protocol: 'https',
hostname: 'assets.example.com',
search: '?v=1727111025337',
},
],
},
}
很高兴知道:上述示例将确保
next/legacy/image
的src
属性必须以https://assets.example.com
开头,并且必须具有精确的查询字符串?v=1727111025337
。任何其他协议或查询字符串都将以 400 Bad Request 响应。¥Good to know: The example above will ensure the
src
property ofnext/legacy/image
must start withhttps://assets.example.com
and must have the exact query string?v=1727111025337
. Any other protocol or query string will respond with 400 Bad Request.
域名
¥Domains
警告:自 Next.js 14 起已弃用,取而代之的是严格的
remotePatterns
,以保护你的应用免受恶意用户的侵害。仅当你拥有该域提供的所有内容时才使用domains
。¥Warning: Deprecated since Next.js 14 in favor of strict
remotePatterns
in order to protect your application from malicious users. Only usedomains
if you own all the content served from the domain.
与 remotePatterns
类似,domains
配置可用于提供外部映像允许的主机名列表。
¥Similar to remotePatterns
, the domains
configuration can be used to provide a list of allowed hostnames for external images.
但是,domains
配置不支持通配符模式匹配,并且无法限制协议、端口或路径名。
¥However, the domains
configuration does not support wildcard pattern matching and it cannot restrict protocol, port, or pathname.
以下是 next.config.js
文件中 domains
属性的示例:
¥Below is an example of the domains
property in the next.config.js
file:
module.exports = {
images: {
domains: ['assets.acme.com'],
},
}
加载器配置
¥Loader Configuration
如果你想使用云提供商来优化图片,而不是使用 Next.js 内置图片优化 API,则可以在 next.config.js
文件中配置 loader
和 path
前缀。这允许你使用图片 src
的相对 URL 并自动为你的提供商生成正确的绝对 URL。
¥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 loader
and path
prefix in your next.config.js
file. 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:
-
默认:自动与
next dev
、next start
或自定义服务器配合使用¥Default: Works automatically with
next dev
,next start
, or a custom server -
Vercel:当你在 Vercel 上部署时自动工作,无需配置。了解更多
¥Vercel: Works automatically when you deploy on Vercel, no configuration necessary. Learn more
-
Imgix:
loader: 'imgix'
-
Cloudinary:
loader: 'cloudinary'
-
Akamai:
loader: 'akamai'
-
风俗:
loader: 'custom'
通过在next/legacy/image
组件上实现loader
属性来使用自定义云提供商¥Custom:
loader: 'custom'
use a custom cloud provider by implementing theloader
prop on thenext/legacy/image
component
如果你需要不同的提供者,可以将 loader
属性与 next/legacy/image
一起使用。
¥If you need a different provider, you can use the loader
prop with next/legacy/image
.
无法使用
output: 'export'
在构建时优化图片,只能按需优化。要将next/legacy/image
与output: 'export'
一起使用,你将需要使用与默认加载器不同的加载器。在讨论中阅读更多内容。¥Images can not be optimized at build time using
output: 'export'
, only on-demand. To usenext/legacy/image
withoutput: 'export'
, you will need to use a different loader than the default. Read more in the discussion.
高级
¥Advanced
以下配置适用于高级用例,通常不是必需的。如果你选择配置以下属性,你将在未来的更新中覆盖对 Next.js 默认值的任何更改。
¥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
如果你知道用户期望的设备宽度,则可以使用 next.config.js
中的 deviceSizes
属性指定设备宽度断点列表。当 next/legacy/image
组件使用 layout="responsive"
或 layout="fill"
时,将使用这些宽度,以确保为用户设备提供正确的图片。
¥If you know the expected device widths of your users, you can specify a list of device width breakpoints using the deviceSizes
property in next.config.js
. These widths are used when the next/legacy/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
你可以使用 next.config.js
文件中的 images.imageSizes
属性指定图片宽度列表。这些宽度与 设备尺寸 数组连接,形成用于生成图片 srcset 的完整尺寸数组。
¥You can specify a list of image widths using the images.imageSizes
property in your next.config.js
file. These widths are concatenated with the array of device sizes to form the full array of sizes used to generate image srcsets.
存在两个单独列表的原因是 imageSizes 仅用于提供 sizes
属性的图片,这表明图片小于屏幕的整个宽度。因此,imageSizes 中的尺寸都应小于 deviceSizes 中的最小尺寸。
¥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
默认 图片优化 API 将通过请求的 Accept
标头自动检测浏览器支持的图片格式,以确定最佳输出格式。
¥The default Image Optimization API will automatically detect the browser's supported image formats via the request's Accept
header in order to determine the best output format.
如果 Accept
标头与多种配置的格式匹配,则使用数组中的第一个匹配项。因此,数组顺序很重要。如果没有匹配(或源图片是 animated),图片优化 API 将回退到原始图片的格式。
¥If the Accept
header 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 (or the source image is animated), 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'],
},
}
你可以启用 AVIF 支持,并使用以下配置回退到 WebP。
¥You can enable AVIF support and still fallback to WebP with the following configuration.
module.exports = {
images: {
formats: ['image/avif', 'image/webp'],
},
}
很高兴知道:AVIF 通常需要多花 50% 的时间来编码,但与 WebP 相比,压缩后体积小 20%。这意味着第一次请求图片时,通常会较慢,然后缓存的后续请求会更快。
¥Good to know: AVIF generally takes 50% 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
下面介绍默认 loader 的缓存算法。对于所有其他加载程序,请参阅你的云提供商的文档。
¥The following describes the caching algorithm for the default loader. For all other loaders, please refer to your cloud provider's documentation.
图片根据请求动态优化并存储在 <distDir>/cache/images
目录中。优化后的图片文件将用于后续请求,直到到期。当发出与缓存但过期的文件匹配的请求时,过期的图片将立即失效。然后,图片在后台再次优化(也称为重新验证)并使用新的到期日期保存到缓存中。
¥Images are optimized dynamically upon request and stored in the <distDir>/cache/images
directory. 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 expired image is served stale immediately. Then the image is optimized again in the background (also called revalidation) and saved to the cache with the new expiration date.
图片的缓存状态可以通过读取 x-nextjs-cache
(部署在 Vercel 上时为 x-vercel-cache
)响应标头的值来确定。可能的值如下:
¥The cache status of an image can be determined by reading the value of the x-nextjs-cache
(x-vercel-cache
when deployed on Vercel) response header. The possible values are the following:
-
MISS
- 该路径不在缓存中(最多出现一次,在第一次访问时)¥
MISS
- the path is not in the cache (occurs at most once, on the first visit) -
STALE
- 该路径在缓存中,但超出了重新验证时间,因此它将在后台更新¥
STALE
- the path is in the cache but exceeded the revalidate time so it will be updated in the background -
HIT
- 该路径在缓存中并且未超过重新验证时间¥
HIT
- the path is in the cache and has not exceeded the revalidate time
过期(或更确切地说是最大期限)由 minimumCacheTTL
配置或上游映像 Cache-Control
标头定义,以较大者为准。具体来说,使用 Cache-Control
报头的 max-age
值。如果同时找到 s-maxage
和 max-age
,则首选 s-maxage
。max-age
还会传递到任何下游客户端,包括 CDN 和浏览器。
¥The expiration (or rather Max Age) is defined by either the minimumCacheTTL
configuration or the upstream image Cache-Control
header, whichever is larger. Specifically, the max-age
value of the Cache-Control
header is used. If both s-maxage
and max-age
are found, then s-maxage
is preferred. The max-age
is also passed-through to any downstream clients including CDNs and browsers.
-
当上游镜像不包含
Cache-Control
头或者该值很低时,你可以配置minimumCacheTTL
来增加缓存持续时间。¥You can configure
minimumCacheTTL
to increase the cache duration when the upstream image does not includeCache-Control
header or the value is very low. -
你可以配置
deviceSizes
和imageSizes
以减少可能生成的图片总数。¥You can configure
deviceSizes
andimageSizes
to reduce the total number of possible generated images. -
你可以将 formats 配置为禁用多种格式,转而使用单一图片格式。
¥You can configure formats to disable multiple formats in favor of a single image format.
最小缓存 TTL
¥Minimum Cache TTL
你可以为缓存的优化图片配置生存时间 (TTL)(以秒为单位)。在许多情况下,最好使用 静态图片导入,它会自动散列文件内容并使用 immutable
的 Cache-Control
标头永久缓存图片。
¥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-Control
header of immutable
.
module.exports = {
images: {
minimumCacheTTL: 60,
},
}
优化映像的过期时间(或更确切地说是最大期限)由 minimumCacheTTL
或上游映像 Cache-Control
标头(以较大者为准)定义。
¥The expiration (or rather Max Age) of the optimized image is defined by either the minimumCacheTTL
or the upstream image Cache-Control
header, whichever is larger.
如果你需要更改每个图片的缓存行为,你可以配置 headers
以在上游图片上设置 Cache-Control
标头(例如 /some-asset.jpg
,而不是 /_next/image
本身)。
¥If you need to change the caching behavior per image, you can configure headers
to set the Cache-Control
header on the upstream image (e.g. /some-asset.jpg
, not /_next/image
itself).
此时没有使缓存失效的机制,所以最好保持 minimumCacheTTL
为低电平。否则,你可能需要手动更改 src
属性或删除 <distDir>/cache/images
。
¥There is no mechanism to invalidate the cache at this time, so its best to keep minimumCacheTTL
low. Otherwise you may need to manually change the src
prop or delete <distDir>/cache/images
.
禁用静态导入
¥Disable Static Imports
默认行为允许你导入静态文件(例如 import icon from './icon.png'
),然后将其传递给 src
属性。
¥The default behavior allows you to import static files such as import icon from './icon.png'
and then pass that to the src
property.
在某些情况下,如果此功能与期望导入行为不同的其他插件发生冲突,你可能希望禁用此功能。
¥In some cases, you may wish to disable this feature if it conflicts with other plugins that expect the import to behave differently.
你可以在 next.config.js
内禁用静态图片导入:
¥You can disable static image imports inside your next.config.js
:
module.exports = {
images: {
disableStaticImages: true,
},
}
危险地允许 SVG
¥Dangerously Allow SVG
由于某些原因,默认 loader 不会优化 SVG 图片。首先,SVG 是一种矢量格式,这意味着它可以无损地调整大小。其次,SVG 具有许多与 HTML/CSS 相同的功能,如果没有适当的 内容安全策略 (CSP) 标头.5,可能会导致漏洞。
¥The default loader does not optimize SVG images for a few reasons. First, SVG is a vector format meaning it can be resized losslessly. Second, SVG has many of the same features as HTML/CSS, which can lead to vulnerabilities without proper Content Security Policy (CSP) headers.
因此,当已知 src
属性是 SVG 时,我们建议使用 unoptimized
属性。当 src
以 ".svg"
结尾时,这种情况会自动发生。
¥Therefore, we recommended using the unoptimized
prop when the src
prop is known to be SVG. This happens automatically when src
ends with ".svg"
.
但是,如果你需要使用默认图片优化 API 提供 SVG 图片,则可以在 next.config.js
中设置 dangerouslyAllowSVG
:
¥However, if you need to serve SVG images with the default Image Optimization API, you can set dangerouslyAllowSVG
inside your next.config.js
:
module.exports = {
images: {
dangerouslyAllowSVG: true,
contentDispositionType: 'attachment',
contentSecurityPolicy: "default-src 'self'; script-src 'none'; sandbox;",
},
}
此外,强烈建议还设置 contentDispositionType
以强制浏览器下载图片,以及设置 contentSecurityPolicy
以阻止执行图片中嵌入的脚本。
¥In addition, it is strongly recommended to also set contentDispositionType
to force the browser to download the image, as well as contentSecurityPolicy
to prevent scripts embedded in the image from executing.
contentDispositionType
默认 loader 将 Content-Disposition
标头设置为 attachment
以增加保护,因为 API 可以提供任意远程图片。
¥The default loader sets the Content-Disposition
header to attachment
for added protection since the API can serve arbitrary remote images.
默认值为 attachment
,强制浏览器在直接访问时下载图片。当 dangerouslyAllowSVG
为真时,这一点尤为重要。
¥The default value is attachment
which forces the browser to download the image when visiting directly. This is particularly important when dangerouslyAllowSVG
is true.
你可以选择配置 inline
以允许浏览器在直接访问时渲染图片,而无需下载它。
¥You can optionally configure inline
to allow the browser to render the image when visiting directly, without downloading it.
module.exports = {
images: {
contentDispositionType: 'inline',
},
}
动画图片
¥Animated Images
默认 loader 将自动绕过动画图片的图片优化并按原样提供图片。
¥The default loader will automatically bypass Image Optimization for animated images and serve the image as-is.
尽力自动检测动画文件,并支持 GIF、APNG 和 WebP。如果你想明确绕过给定动画图片的图片优化,请使用 unoptimized 属性。
¥Auto-detection for animated files is best-effort and supports GIF, APNG, and WebP. If you want to explicitly bypass Image Optimization for a given animated image, use the unoptimized prop.
版本历史
¥Version History
版本 | 变化 |
---|---|
v13.0.0 | next/image 更名为 next/legacy/image |