Skip to content

Instantly share code, notes, and snippets.

@dryleaf
Last active March 25, 2021 02:18
Show Gist options
  • Save dryleaf/9cae14913b3374dfbf86eeed98687c2f to your computer and use it in GitHub Desktop.
Save dryleaf/9cae14913b3374dfbf86eeed98687c2f to your computer and use it in GitHub Desktop.

1. Adding webpack bundle analyzer to NextJs app (Production)

a) Install webpack bundle analyzer as a dev dependancy

npm install --save-dev webpack-bundle-analyzer

or

yarn add -D webpack-bundle-analyzer

b) Install cross-env as well

  • so that we can pass environment variables
npm install --save-dev cross-env

or

yarn add -D cross-env

2. Initialize webpack analyzer into your next.config.js file

const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer')
// This is important so that you control when to build next app with bundle analyzer
const isAnalyze = typeof process.env.BUNDLE_ANALYZE !== "undefined";

module.exports = {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    if (isAnalyze) {
      config.plugins.push(new BundleAnalyzerPlugin({
        analyzerMode: 'server',
        analyzerPort: isServer ? 1111 : 1112, // configure server/client ports separately
        openAnalyzer: true,
      }));
    }
    return config
  },
}

3. Add build:analyze into your package.json > scripts section

  • In case you don't use a custom express server, only use the alternative line with next dev and next start line
{
  ...
  ...
  "scripts": {
-   "dev": "node server.js",
+   "dev": "next dev",
    "build": "next build",
    "build:analyze": "cross-env BUNDLE_ANALYZE=true next build",
-   "start": "cross-env NODE_ENV=production node server.js"
+   "start": "next start"
  },
  ...
  ...
  ...
  "devDependencies": {
    "cross-env": "^5.2.1",
    "webpack-bundle-analyzer": "^4.4.0"
  }
}

4. Finally, build code with analyzer

npm run build:analyze

or

yarn build:analyze

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment