Recently I helped my friend to analyze why his Next.js project is slow. I installed @next/bundle-analyzer
which can help us to analyze the bundle size. I follow their guideline for configuration
yarn add @next/bundle-analyzer
Update next.config.js
:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
i18n: {
locales: ['en', 'vi'],
defaultLocale: 'vi',
localeDetection: false,
},
}
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer(nextConfig)
ANALYZE=true yarn build
, it throws an error:yarn run v1.22.19
$ next build
- info Loaded env from /root/Frontend/.env.production
- info Loaded env from /root/Frontend/.env
- info Linting and checking validity of types
Failed to compile.
./node_modules/opener/lib/opener.js
Module not found: Can't resolve 'child_process'
https://nextjs.org/docs/messages/module-not-found
Import trace for requested module:
./node_modules/webpack-bundle-analyzer/lib/utils.js
./node_modules/webpack-bundle-analyzer/lib/viewer.js
./node_modules/webpack-bundle-analyzer/lib/index.js
./node_modules/@next/bundle-analyzer/index.js
./next.config.js
./hooks/useAnalyzeUrl.js
./PageComponents/AnalyzePage/AnalyzePage.js
./pages/analyze/index.js
> Build failed because of webpack errors
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I found a solution from here. Basically we need to disable child_process
and fs
in webpack config. Here is the final next.config.js
:
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
compress: false,
i18n: {
locales: ['en', 'vi'],
defaultLocale: 'vi',
localeDetection: false,
},
+ webpack: (config, { isServer }) => {
+ if (!isServer) {
+ config.resolve.fallback.fs = false
+ config.resolve.fallback.child_process = false
+ }
+ return config
+ },
}
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer(nextConfig)