2019-02-28 19:21:31 +01:00
# Next.js + Webpack Bundle Analyzer
Use `webpack-bundle-analyzer` in your Next.js project
## Installation
```
2021-07-26 18:43:07 +02:00
npm install @next/bundle -analyzer
2019-02-28 19:21:31 +01:00
```
or
```
2021-07-26 18:43:07 +02:00
yarn add @next/bundle -analyzer
2019-02-28 19:21:31 +01:00
```
2021-07-26 18:43:07 +02:00
Note: if installing as a `devDependency` make sure to wrap the require in a `process.env` check as `next.config.js` is loaded during `next start` as well.
2019-02-28 19:21:31 +01:00
### Usage with environment variables
Create a next.config.js (and make sure you have next-bundle-analyzer set up)
```js
2019-05-29 13:57:26 +02:00
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
module.exports = withBundleAnalyzer({})
2019-02-28 19:21:31 +01:00
```
2020-07-09 10:24:21 +02:00
Or configuration as a function:
```js
module.exports = (phase, defaultConfig) => {
return withBundleAnalyzer(defaultConfig)
}
```
2019-02-28 19:21:31 +01:00
Then you can run the command below:
```bash
# Analyze is done on build when env var is set
ANALYZE=true yarn build
```
When enabled two HTML files (client.html and server.html) will be outputted to `<distDir>/analyze/` . One will be for the server bundle, one for the browser bundle.
2020-08-16 17:25:51 +02:00
### Usage with next-compose-plugins
From version 2.0.0 of next-compose-plugins you need to call bundle-analyzer in this way to work
```js
const withPlugins = require('next-compose-plugins')
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
})
2020-11-11 09:02:43 +01:00
2020-08-16 17:25:51 +02:00
module.exports = withPlugins([
2020-11-11 09:02:43 +01:00
[withBundleAnalyzer],
2020-08-16 17:25:51 +02:00
// your other plugins here
])
```