next/image をビルド時に最適化する
takeharak
next/image を next export で使う
今回の環境
TL;DR
1. next-export-optimize-images をインストール
npm install --save-dev next-export-optimize-images
2. next.config.js にプラグインを追加
// next.config.js
+ const withExportImages = require('next-export-optimize-images')
+
/** @type {import('next').NextConfig} */
const nextConfig = {
/* config options here */
}
- module.exports = nextConfig
+ module.exports = withExportImages(nextConfig)
3. 設定を追加
// export-images.config.js
+ /** @type {import('next-export-optimize-images').Config} */
+ const config = {
+ basePath: process.env.NEXT_PUBLIC_BASE_PATH ?? '',
+ sharpOptions: {
+ webp: {
+ effort: 0,
+ },
+ avif: {
+ effort: 0,
+ }
+ },
+ convertFormat: [
+ ['png', 'webp'],
+ ['jpg', 'avif'],
+ ],
+ }
+
+ module.exports = config
4. next/image を使用
+ import Image from 'next/image'
+ <Image
+ placeholder="blur"
+ src="/example.png"
+ alt="example"
+ width={500}
+ height={500}
+ />
5. コマンドを追加
// .github/deploy.yml
...
- name: Build
run: npm run build
- name: Export
run: npx -y next export
+ - name: Optimize Images
+ run: npx -y next-export-optimize-images
...