Closed1
@next/bundle-analyzerが本番環境で読み込まれないようにする
next build
でビルド + next start
でNext.jsを動かしている
背景1)- 現在のプロジェクトではNext.jsをGAE(Google App Engine)で動かしている
- GAEでNext.jsを動かすには「
next build
でビルド +next start
で起動」という形になる
@next/bundle-analyzer
を導入
背景2)Next.jsのプロジェクトで- パフォーマンスチューニングのためにバンドルサイズを可視化できる
@next/bundle-analyzer
を導入 -
READMEには以下のような導入手順が紹介されている
npm install @next/bundle-analyzer
-
next.config.js
で以下のように記述const withBundleAnalyzer = require('@next/bundle-analyzer')({ enabled: process.env.ANALYZE === 'true', }) module.exports = withBundleAnalyzer({ ここにconfig })
- 本番環境では使わないと思い
@next/bundle-analyzer
をdevDependencies
に追加した
発生した問題
- 本番環境(実際にはステージング環境)で
next start
実行時に次のエラーが発生Error: Cannot find module '@next/bundle-analyzer'
-
next start
での起動時にはnext.config.js
が読み込まれるらしくrequire('@next/bundle-analyzer')
の部分でエラーになっていた
対応
ドキュメントに書かれているとおり、devDependencies
ではなくdependencies
に入れれば解決する。しかし、本番環境でのインスタンス起動時に余計なものをrequireしたくない(起動時間に影響を及ぼす可能性もある)。
そこで以下のように記述することにした。
const withBundleAnalyzer = process.env.ANALYZE === 'true'
? require('@next/bundle-analyzer')({ enabled: true })
: (config) => config;
module.exports = withBundleAnalyzer({ ここにconfig })
これなら環境変数でANALYZE=true
を指定しない限りrequireは実行されない。もちろん@next/bundle-analyzer
はdevDependencies
のままでOK。
このスクラップは2021/10/12にクローズされました