Image 组件

2026年9月6日

next/image 包在 <img> 外面:按设备出合适尺寸、优先现代格式、占位防 CLS、默认懒加载。原生 <img> 仍然能用,只是没有这套优化。


本地文件

图放 public/src/ 开头,宽高必填(静态 import 除外):

import Image from "next/image";

export default function Page() {
  return (
    <Image src="/cover.png" width={800} height={450} alt="封面" />
  );
}
tsx

静态 import

构建能读到文件时,框架自己算宽高:

import Image from "next/image";
import cover from "@/public/cover.png";

<Image src={cover} alt="封面" />
tsx

tsconfig 里如果要 @/public/*,自己加一条 paths。本仓库用 /public 即可。


远程图

默认不允许任意域名。先在 next.config 登记:

import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "images.example.com",
        pathname: "/media/**",
      },
    ],
  },
};

export default nextConfig;
ts

漏配会报 Invalid src prop,hostname 不在允许名单里。

<Image
  src="https://images.example.com/media/1.webp"
  width={192}
  height={108}
  alt=""
/>
tsx

LCP 图不要懒加载

Image 默认 loading="lazy"。首屏最大那张(LCP)会被警告,改成立即加载:

<Image src={hero} alt="" loading="eager" />
tsx

或对靠前的几张设 preload(具体 prop 名以你当前 Next 版本文档为准,新版本常用 priority):

<Image src={hero} alt="" priority />
tsx

格式和断点

框架看请求的 Accept,能出 AVIF / WebP 就出。可以显式打开:

images: {
  formats: ["image/avif", "image/webp"],
  deviceSizes: [640, 750, 828, 1080, 1200, 1920],
  imageSizes: [16, 32, 48, 64, 96, 128, 256, 384],
}
ts

imageSizes 给头像、图标这类小图,deviceSizes 给横幅、全宽图。再靠 sizes 告诉浏览器这张图实际占多宽:

<Image src={cover} alt="" sizes="(max-width: 768px) 100vw, 50vw" />
tsx

常用 props

必填: srcalt。静态 import 时可省略宽高。

类别属性作用
尺寸width / height / fill / sizesfill 铺满相对定位的父级
质量quality(默认约 75)、unoptimized关优化则原图
加载loadingpriorityplaceholder="blur"blurDataURL模糊占位要一张很小的 data URL
事件onLoadonError客户端组件里更常见

远程图域名、LCP、sizes 这三件事弄对,比把所有 prop 背完更有用。

下一篇:next/font,避免字体把版面撑歪。


参考文档