🦔
Next.js 13を見据えたnext/imageの使い方
Next.js 13と12.3のnext/imageの違い
Next.js 13では、next/imageに以下のような変更が加えられています。
<span> wrapper removed. layout, objectFit, objectPosition, lazyBoundary, lazyRoot props removed. alt is required. onLoadingComplete receives reference to img element. Built-in loader config removed.
Next 12.3では、next/imageを使うと以下のように<span>タグの中に<img>タグがレンダリングされる形式でした。
<span> <!-- position: relative; -->
<span></span>
<img> <!-- position: absolute; -->
</span>
Next 13では、<span>で囲われず、そのまま<img>タグがレンダリングされるようになりました。
next/future/imageを使うには
以下の対応が必要です。
-
next/future/imageをimportする - next.config.jsに
experimentalを追加する
import Image from 'next/image';
// ↓に変える
import Image from 'next/future/image';
以下はexperimentalを追加したnext.config.jsの例です。
next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
experimental: {
images: {
allowFutureImage: true
}
},
}
module.exports = nextConfig
公式の実装例
- https://github.com/vercel/next.js/tree/canary/examples/image-component
- https://stackblitz.com/github/vercel/next.js/tree/canary/examples/image-component
Next.jsは公式が実装例を沢山公開してくれているので、とても使いやすいですね。
Discussion