概要
next/image の Image コンポーネントを使うと、画像の自動リサイズ・WebP 変換・遅延読み込み(loading="lazy")が自動適用される。
通常の <img> タグと比べてパフォーマンスと Core Web Vitals(CLS)改善に直結する。
インストール
# 追加インストールは不要
ローカル画像の表示
// src/app/page.tsx
import Image from "next/image";
import heroImage from "@/public/hero.png";
export default function HomePage() {
return (
<main className="p-6">
{/* ローカル画像は import すると width / height が自動設定される */}
<Image
src={heroImage}
alt="ヒーロー画像"
priority // LCP 対象画像には priority を付ける
className="rounded"
/>
</main>
);
}
外部ドメイン画像の表示
// src/components/AvatarImage.tsx
import Image from "next/image";
type Props = { src: string; name: string };
export function AvatarImage({ src, name }: Props) {
return (
<Image
src={src}
alt={`${name} のアバター`}
width={64}
height={64}
className="rounded-full"
/>
);
}
// next.config.ts(外部ドメインを許可する)
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
images: {
remotePatterns: [
{
protocol: "https",
hostname: "avatars.githubusercontent.com",
},
],
},
};
export default nextConfig;
コンテナに合わせて fill で表示
// src/components/CoverImage.tsx
import Image from "next/image";
type Props = { src: string; alt: string };
export function CoverImage({ src, alt }: Props) {
return (
// fill を使う場合は親要素に relative と明示的なサイズが必要
<div className="relative h-48 w-full overflow-hidden rounded">
<Image
src={src}
alt={alt}
fill
sizes="(max-width: 768px) 100vw, 50vw"
className="object-cover"
/>
</div>
);
}
ポイント
- ローカル画像を
importするとwidth/heightが自動付与される(手動指定不要) - 外部ドメイン画像は
next.config.tsのremotePatternsに追加しないと表示されない - LCP(最大コンテンツ描画)対象の画像には
priorityを付けて事前読み込みする fillは親要素がposition: relativeで固定サイズを持つ必要があるsizesを正確に設定すると、デバイス幅に応じた最適サイズが配信される