Skip to content

Instantly share code, notes, and snippets.

@dryleaf
Last active March 25, 2021 02:18
Show Gist options
  • Select an option

  • Save dryleaf/9cae14913b3374dfbf86eeed98687c2f to your computer and use it in GitHub Desktop.

Select an option

Save dryleaf/9cae14913b3374dfbf86eeed98687c2f to your computer and use it in GitHub Desktop.
## Add webpack bundle analyzer
### Install webpack bundle analyzer as a dev dependancy
```
npm install --save-dev webpack-bundle-analyzer
```
or
```
yarn add -D webpack-bundle-analyzer
```
### please install cross-env as well (so that we can pass environment variables)
```
npm install --save-dev cross-env
```
or
```
yarn add -D cross-env
```
## 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 and client ports separately, whatever you want (*^_^*)
openAnalyzer: true,
}));
}
return config
},
}
```
## 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
```diff
{
...
...
"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"
}
}
```
## Finally, we build production ready code with analyzer
```
npm run build:analyze
```
or
```
yarn build:analyze
```
**References**
- https://excitoninteractive.com/articles/read/65/webpack4/step-by-step-bundle-analyzer-plugin
- https://nextjs.org/docs/api-reference/next.config.js/custom-webpack-config
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment