How to analyze Next Js bundle size and content

Viewed 10729

I've just upgrated to Next JS 9.0 and when I run a build there's a fantastic new feature which shows you the size of all the compiled pages. They're all around 20-30k except for pages which use Formik which tend to be at least double that size. The main problem is that the app.js file is over 600k and red.

Is there a way to dive further and see on a more granular level what's making up all my bundles?

2 Answers
  1. Install @next/bundle-analyzer and cross-env as dev dependency:

    yarn add -D @next/bundle-analyzer cross-env
    
  2. Create a next.config.js file in the root of your project directory (next to package.json) and paste the code below:

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

module.exports = withBundleAnalyzer({
  reactStrictMode: true,
})
  1. Go to your package.json file and add the line below to the scripts section:

    "analyze": "cross-env ANALYZE=true next build"
    

Now you can run yarn analyze or npm run analyze to analyze your bundle size.

Related