なぜ画像を最適化する必要があるのか
-
Next.jsは一番上の階層にある
/publicフォルダの中に画像のようなstatic assetsを配置することで、アプリケーションの中からそれぞれのファイルに参照することが出来る。 -
next/imageコンポーネントを使うことで、従来のHTMLでやっていたような、画像周りについて最適化するために必要なことを自動的に出来る。- 異なる画面幅に対してリスポンシブルにサイズを変更する
- 異なるデバイスに対して画像のサイズを指定する
- 画像のロードにかかるレイアウトシフトを防ぐ
- ユーザーのビューポートの外にある要素に関してLazyLoadして描画をしないようにする
Next.jsにおけるコンポーネントの特徴
-
<Image>コンポーネントは、HTMLのタグの
extensionである。 - 自動的に画像を最適化する機能を有している。
- 上記で上げた特徴のほかに、ブラウザがサポートする限り
WEBP形式やAVIF形式の画像についても配信する。
The Component is an extension of the HTML
tag, and comes with automatic image optimization, such as:
・Preventing layout shift automatically when images are loading.
・Resizing images to avoid shipping large images to devices with a smaller viewport.
・Lazy loading images by default (images load as they enter the viewport).
・Serving images in modern formats, like WebP and AVIF, when the browser supports it.
コードを書いてみよう
/// /app/page.tsx
import AcmeLogo from '@/app/ui/acme-logo';
import { ArrowRightIcon } from '@heroicons/react/24/outline';
import Link from 'next/link';
import { lusitana } from '@/app/ui/fonts';
+ import Image from 'next/image';
export default function Page() {
return (
// ...
<div className="flex items-center justify-center p-6 md:w-3/5 md:px-28 md:py-12">
{/* Add Hero Images Here */}
+ <Image
+ src="/hero-desktop.png"
+ width={1000}
+ height={760}
+ className="hidden md:block"
+ alt="Screenshots of the dashboard project showing desktop version"
+ />
</div>
//...
);
}
- ホームページ上に
/publicに格納された/hero-desktop.jpgが表示される。 - Width=1000, Height=760と明示的に指定されているが、これはアスペクト比を計算する点とレイアウトシフトを防ぐ観点から非常に重要で、画像のサイズとアスペクト比と実際の画像のアスペクト比は同じ値に設定しておくことが必要。
参考