How to configure bundle analyzer

Install the bundle analysis package.

npm install --save-dev @next/bundle-analyzer

Then configure nextjs.config to use the package.

const withBundleAnalyzer = require('@next/bundle-analyzer')({ 
enabled: process.env.ANALYZE === 'true', 
}); 
 
module.exports = withBundleAnalyzer({ // Other Next.js configuration options here });

Run ANALYZE=true npm run build and it will open up a new browser to show bundle analysis report.

It shows 3 different parts - node modules, edge, and client.

Interpretation the output of the bundle analyzer

Each rectangle represents a module or package. The size of a rectangle shows how large or tiny the module or package is compared to others.

  • Stat size: The size of the JavaScript bundle when served to the client; this is the size of the JavaScript code that the client’s web browser has to download and execute to run the app
  • Parsed size: The size of the bundle after the web browser has parsed it; this is the amount of memory that the JavaScript code takes up in the web browser after it has executed the code
  • Gzipped size: The size of the JavaScript bundle when compressed using the Gzip algorithm; this is the amount of data the client’s web browser must download to run the app. Gzip is a common compression algorithm used to reduce the size of web assets like JavaScript files. It can significantly reduce the amount of data transferred over the network.

How to use analyzer

With interpretation,

  • Find large dependencies and look for alternatives
  • Find duplicated code
  • Identify unused code find unused import, export, variables, lines of code