この記事では Next.js で Bundle Analyzer(@next/bundle-analyzer)を使ってバンドルサイズを可視化する手順をまとめます。pnpm を使った環境での例を示しますが、npm / yarn でも同様です。
目的:
この記事のゴールは、下記のコマンドで解析を行い、ブラウザで結果を確認できるようにすることです。
pnpm analyzepnpm add -D -E @next/bundle-analyzernext.config.js を修正/** @type {import('next').NextConfig} */
// CommonJS (defaultのnext.config.jsがCommonJSの場合)
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
const nextConfig = {
//...
}
module.exports = withBundleAnalyzer(nextConfig)ESMの例:
import withBundleAnalyzer from '@next/bundle-analyzer'
const enabled = process.env.ANALYZE === 'true'
const nextConfig = {
// ...
}
export default withBundleAnalyzer({ enabled })(nextConfig)package.json のscriptsを修正{
"scripts": {
"analyze": "ANALYZE=true next build"
},
}以上でBundle Analyzerでバンドルサイズの確認ができるようになります。
解析を実行
pnpm analyze出力場所
解析結果はビルド出力の下に .next/analyze 配下に HTML として出力されます。生成されるファイルは環境や Next.js のバージョンによって若干変わることがありますが、基本的には HTML ファイルなのでブラウザで開いて確認できます。
ローカルで見る(簡易サーブ)
macOS / Linux で簡単に開く方法:
# Finder / ファイルブラウザで開く(macOS)
open .next/analyze/index.html
# もしくは簡易HTTPサーバで配信してブラウザで確認
npx http-server .next/analyze -c-1
# または
npx serve .next/analyzeWarning
--turbopack オプション)や、Next の将来バージョンでは本プラグインが動作しないことがあります。Bundle Analyzer は主に webpack ベースのビルド向けです。ANALYZE=true next build のように環境変数で有効化する方法は macOS / Linux ではそのまま動作しますが、Windows の CMD では動きません。クロスプラットフォームに対応するには cross-env を使ってください。"scripts": {
"analyze": "ANALYZE=true next build",
"analyze:open": "pnpm analyze && open .next/analyze",
"analyze:server": "pnpm analyze && npx http-server .next/analyze -c-1"
}analyze:open: 解析結果を開く(macOS 向け)analyze:server: Dev Containerを使用している場合などは簡易HTTPサーバで配信してブラウザで確認以上で Bundle Analyzer によるバンドル確認が可能になります。
