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
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
},
}
- In case you don't use a custom express server, only use the alternative line with
next dev
andnext 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"
}
}
npm run build:analyze
or
yarn build:analyze