How to analyze Next.js application bundles

Learn more about what is in the Next.js app bundle

Next provides us with a way to analyze the generated code package.

Open the package.json file of the application and add these 3 new commands in the script section:

"analyze": "cross-env ANALYZE=true next build",
"analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
"analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build"

like this:

{
  "name": "firstproject",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start",
    "analyze": "cross-env ANALYZE=true next build",
    "analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
    "analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "next": "^9.1.2",
    "react": "^16.11.0",
    "react-dom": "^16.11.0"
  }
}

Then install these two packages:

npm install --dev cross-env @next/bundle-analyzer

Createnext.config.jsThe file is placed in the root directory of the project, and the content is as follows:

const withBundleAnalyzer = require('@next/bundle-analyzer')({
  enabled: process.env.ANALYZE === 'true'
})

module.exports = withBundleAnalyzer({})

Now run the command

npm run analyze

This will open 2 pages in the browser. One is for client binding, and the other is for server binding:

This is very useful. You can check the space in the bundle that takes up the most space, and you can also use the sidebar to exclude the bundle to visualize smaller bundles more easily:

Download mine for freeNext.js manual


More tutorials next: