概要
next/image の Image コンポーネントは以下を自動的に行う。
- WebP / AVIF への変換
- 遅延読み込み(lazy loading)
srcsetによる適切なサイズ配信- Cumulative Layout Shift(CLS)防止
基本的な使い方
import Image from "next/image";
export function Avatar() {
return (
<Image
src="/avatar.png"
alt="ユーザーアバター"
width={64}
height={64}
className="rounded-full"
/>
);
}
fill で親要素いっぱいに表示する
import Image from "next/image";
export function HeroImage() {
return (
<div className="relative h-64 w-full">
<Image
src="/hero.jpg"
alt="ヒーロー画像"
fill
sizes="100vw"
className="object-cover"
priority // Above the fold の画像は priority を付ける
/>
</div>
);
}
外部ドメインの画像を許可する
// next.config.ts
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "example.com",
pathname: "/images/**",
},
],
},
};
export default nextConfig;
// 外部ドメインの画像
import Image from "next/image";
export function ExternalImage() {
return (
<Image
src="https://example.com/images/photo.jpg"
alt="外部画像"
width={400}
height={300}
/>
);
}
ポイント
width/heightは必須(fillを使う場合は不要)- ファーストビューに表示される画像には
priorityを付けて LCP を改善する sizes属性を指定すると適切な解像度の画像が配信されるobject-fitはclassNameでobject-cover/object-containを指定する