No img element
防止使用
<img>
元素,因为它会导致 LCP 速度变慢和带宽更高。
为什么会出现此错误
使用了 <img>
元素来显示图像,而不是 next/image
中的 <Image />
。
可能的修复方法
- 使用
next/image
通过自动 图像优化 来提高性能。
注意:如果部署到托管服务提供商,请记住检查提供商的定价,因为优化的图像的收费可能与原始图像不同。
常见图像优化平台定价
注意:如果自托管,请记住安装
sharp
并检查您的服务器是否有足够的存储空间来缓存优化的图像。
pages/index.js
import Image from 'next/image'
function Home() {
return (
<Image
src="https://example.com/hero.jpg"
alt="Landscape picture"
width={800}
height={500}
/>
)
}
export default Home
- 如果您想使用
next/image
功能(例如模糊占位符),但禁用图像优化,则可以使用 unoptimized 来实现。
pages/index.js
import Image from 'next/image'
const UnoptimizedImage = (props) => {
return <Image {...props} unoptimized />
}
- 您还可以将
<picture>
元素与嵌套的<img>
元素一起使用
pages/index.js
function Home() {
return (
<picture>
<source srcSet="https://example.com/hero.avif" type="image/avif" />
<source srcSet="https://example.com/hero.webp" type="image/webp" />
<img
src="https://example.com/hero.jpg"
alt="Landscape picture"
width={800}
height={500}
/>
</picture>
)
}
- 您可以使用自定义图像加载器来优化图像。将 loaderFile 设置为自定义加载器的路径。
next.config.js
module.exports = {
images: {
loader: 'custom',
loaderFile: './my/image/loader.js',
},
}
实用链接
这有帮助吗?