Bundle Analysis on Next.js Apps
Analyzing your app size is crucial for ensuring your project takes up only a little space. Otherwise, the web load times can be massive and affect the loading speed on the users' browsers.
We have to make sure our app takes up the minimal space possible. To achieve that, we require some tools. So I want to share one of the best npm packages for Next.js apps. It is the @next/bundle-analyzer package.
We have to configure the scripts required for running the analysis, once we had already installed the package.
ANALYZE=true npm run build
When we run the command, the package yields three files: client.html
, nodejs.html
, and edge.html
. The edge file doesn't work yet. We have to focus on the other two files. The modejs file will say the amount of the bundles on the server side, the same for the client file, although for the client side.
We can open the files on the browser. We will see a set of boxes showing the size of the JavaScript modules used on the bundle.
We can identify the following:
Packages are taking up quite a size.
Unused JavaScript files.
Duplicated packages on the bundle.
Besides, we will see green on the console when Analyzer considers it a reasonable file size. Instead, we will see red when the package finds the files that take up much space on the bundle. Therefore, we have to focus on decreasing the file size set to red.
For decreasing the bundle, we have different available strategies:
Dynamic imports. We can import our packages when needed. For example, if we have a modal, we only want to import the package required in the modal when we want to open it.
Change how we import from libraries. A good example we can find it on lodash or material ui packages. Depending on how we import certain functions or components, we will have a bigger o smaller bundle size.
We are not using useEffect when it is not required. If we can show data from the server with Next.js, we can offer data directly after we have made the request. It is not necessary to save the data in the React state.
Conclusion
A smaller bundle size helps to achieve better loading times on our web pages. In addition, we can use tools like @next/bundle-analyzer package to spot where we can improve our project.
Finally, what we want on our apps is as tiny a bundle size as possible for having web applications very smooth and fast.
Here, I share 2 helpful resources that also talk about this topic. I strongly recommend them:
How to analyze your Next.js app bundles by Timonwa Akintokun
How to easily reduce your NextJS bundle size by 30%? by Flavien Bonvin
I hope you enjoyed the article.
Join my weekly newsletter, where I share articles to help you become a better front-end developer. You'll receive them directly to your inbox.
If you have any questions, feel free to contact me on LinkedIn, Edi Rodriguez, or leave a comment in the post.
See you in the next post.
Have a great day!