Wanna see something cool? Check out Angular Spotify 🎧

@next/bundle-analyzer throw error Module not found: Can't resolve child_process

Problem

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

  1. yarn add @next/bundle-analyzer
  2. 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)
  1. Finally, run 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.

Solution

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)
Published 16 Sep 2023

    Read more

     — Angular Material 15 Migration
     — Angular augmenting native elements
     — Upgrading from Angular 12 to 15 in Nx Workspace: A Comprehensive Guide
     — nx:run-commands output not colored
     — Prettier - prevent HTML closing tag > being placed on a new line?

    Follow @trungvose on Twitter for more!