レビュー済み·難易度: 初級·更新: 2026-04-17

Next.js の Image コンポーネントで画像を最適化する

next/image を使い、自動リサイズ・WebP 変換・遅延読み込みを設定する実装例。外部ドメイン画像の許可設定も含む。

nextjsperformanceui-component

対応バージョン

nextjs 15

前提環境

Next.js の基本的なページ・コンポーネント構成を理解していること

概要

next/imageImage コンポーネントを使うと、画像の自動リサイズ・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.tsremotePatterns に追加しないと表示されない
  • LCP(最大コンテンツ描画)対象の画像には priority を付けて事前読み込みする
  • fill は親要素が position: relative で固定サイズを持つ必要がある
  • sizes を正確に設定すると、デバイス幅に応じた最適サイズが配信される

注意点

width と height は必須(レイアウトシフト防止のため)。外部ドメイン画像を使う場合は next.config.ts の remotePatterns に追加が必要。fill を使う場合は親要素に position: relative と明示的なサイズが必要。

関連サンプル