跳到内容
文档错误无 img 元素

无 img 元素

禁止使用 <img> 元素,因为它会导致 LCP 变慢和带宽占用更高。

此错误发生的原因

使用了 <img> 元素来显示图片,而不是 next/image 中的 <Image />

可能的解决方法

  1. 使用 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
  1. 如果您想使用 next/image 功能(例如模糊占位符)但禁用图片优化,您可以使用 unoptimized 来实现
pages/index.js
import Image from 'next/image'
 
const UnoptimizedImage = (props) => {
  return <Image {...props} unoptimized />
}
  1. 您也可以使用嵌套了 <img> 元素的 <picture> 元素
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>
  )
}
  1. 您可以使用自定义图像加载器来优化图像。将 loaderFile 设置为您的自定义加载器的路径。
next.config.js
module.exports = {
  images: {
    loader: 'custom',
    loaderFile: './my/image/loader.js',
  },
}