Hands-On Full-Stack Web Development with GraphQL and React
上QQ阅读APP看书,第一时间看更新

Analyzing bundle size

People that are trying to use as little bandwidth as possible will want to keep their bundle size low. I recommend that you always keep an eye on this, especially when requiring more modules via npm. In this case, you can quickly end up with a huge bundle size, since npm packages tend to require other npm packages themselves.

To protect us against this, we need a method to analyze the bundle size. Only the production build is worth checking. As previously mentioned, the development build includes React in a development release with source maps and so on.

Thanks to webpack, there is a simple solution for analyzing our bundle. This solution is called webpack-bundle-analyzer, and it does exactly what it sounds like.

Install this with the following:

npm install --save-dev webpack-bundle-analyzer

You then need to add two commands to the scripts object in the package.json:

  • "stats": "webpack --profile --json --config webpack.client.build.config.js > stats.json"
  • "analyze": "webpack-bundle-analyzer stats.json"

The first command creates a production build as well as a stats.json file in the root folder. This file holds the information we need.

The analyze command spins up the webpack-bundle-analyzer, showing us how our bundle is built together and how big each package that we use is.

Do this as follows: 

npm run stats
npm run analyze

You can visually see our bundle and package sizes. Remove unnecessary packages in your projects and see how your bundle is reorganized. You can take an example from the following screenshot:

This diagram looks a lot like WinDirStat which is a software to display the disk usage of your computer. We can identify the packages that make up the majority of our bundle.