Next.js: Output webpack stats

To output the webpack stats JSON file on Next.js, you can use a dedicated webpack plugin like FormidableLabs/webpack-stats-plugin.

Step 1. Install webpack-stats-plugin

npm install --save-dev webpack-stats-plugin
yarn add --dev webpack-stats-plugin
pnpm add -D webpack-stats-plugin

Step 2. Configure

next.config.js
const { StatsWriterPlugin } = require('webpack-stats-plugin')
module.exports = {
webpack: (config, options) => {
const { dev, isServer } = options;
// Output webpack stats JSON file only for client-side/production build
if (!dev && !isServer) {
config.plugins.push(
new StatsWriterPlugin({
filename: '../webpack-stats.json',
stats: {
assets: true,
entrypoints: true,
chunks: true,
modules: true
}
)
);
}
return config;
}
};

To avoid issues with other tools that are checking if the repository has uncommitted changes or if you are publishing your project as a npm package, consider adding the generated webpack stats file to .gitingore / .npmignore.

.gitignore
webpack-stats.json
.npmignore
webpack-stats.json


Need help?Contact us via email, Twitter, or GitHub!