'How to build bundle-stats.json in create react app?
I need to build bundle-stats.json to work with webpack-bundle-analyzer. Here how i'm trying build it , but it does not creating any file.
npm run build -- --stats
Could you please help me
Solution 1:[1]
stats have been remove from CRA see
It's recommended to use source-map-explorer
npm i -g source-map-explorer
source-map-explorer 'build/static/js/*.js'.
Solution 2:[2]
Solution 3:[3]
You can do it with @craco/craco which is a tool to use a custom webpack configuration with Create React App.
As explained on this article:
- Install
@craco/cracoandwebpack-bundle-analyzernpm install @craco/craco webpack-bundle-analyzer --save-dev - Create a file named
craco.config.jsin the root of your project folder with this content:const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin; module.exports = function () { return { webpack: { plugins: [new BundleAnalyzerPlugin({ analyzerMode: "server" })], }, }; }; - Add this "analyze" script to your
package.jsonscripts sections:{ ... "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test", "eject": "react-scripts eject", + "analyze": "craco build" } } - Now run:
npm run analyze
Because you set the analyzerMode to "server" in your craco config, you will automatically get your browser open with the results served as a webpage (you can use the "json" option if you want the output without involving the browser)
Solution 4:[4]
Firstly, add the webpack-bundle-analyzer to your dev dependecies:
yarn add -D webpack-bundle-analyzer
Then you can sequentially run commands:
yarn build -- --stats
yarn webpack-bundle-analyzer ./build/bundle-stats.json
Or, for your convenience, you can add the script to your package.json:
"scripts": {
...
"analyze": "yarn build -- --stats && yarn webpack-bundle-analyzer ./build/bundle-stats.json"
}
Instead of yarn you can use npm, just edit the command accordingly.
Then you can run the script using yarn analyze or the scripts runner UI available in VS Code like I do. You can also add a script for deleting the build folder if this already exists before creating a new one. For this, dependently on your platform, you can use the cmd or bash command:
- cmd:
if exist build\\ ( rmdir /s /q .\\build ) - bash:
[ -d 'build' ] && rm -r build
So the final solution will look like this:
"scripts": {
...
"analyze": "yarn remove_build && yarn build -- --stats && yarn webpack-bundle-analyzer ./build/bundle-stats.json",
"remove_build": "if exist build\\ ( rmdir /s /q .\\build )"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | David Villamizar |
| Solution 3 | Mohsen Taleb |
| Solution 4 |
