In this article, We will discuss how we can reduce the javascript bundle size in next.js.
Before discussing the optimization techniques, we are discussing how we know which libraries are heavy in size. Which increases our bundle size.
For next.js, we can use @next/bundle-analyzer to analyze the javascript bundle which libraries are making the bundle heavy in size.
Walkthrough the documentation to understand the bundle analyzer tool.
Next.js provides several built-in optimizations for optimizing JavaScript bundles in your application. Here are some ways to optimize your Next.js JavaScript bundles:
- > Lazy loading: Load only the components that are currently needed, reducing the initial bundle size. Load the library or component when it is actually used like on Button Click or on a Page Load. For Example: –
In the image above, we are loading the fresh chat script when a component actually mounts on the screen. Fresh Chat is only used on a specific page. So, there is no need to load these libraries which are used only on specific screens.
- > Code splitting: Next.js automatically splits your code into smaller chunks, so that only the necessary code is loaded for each page.
- > Dynamic imports: Import components and modules only when they are needed, improving load times.
Read the Documentation to know more about Dynamic Imports. - > Efficient caching: Next.js caches assets, components, and data on the client to reduce the amount of data that needs to be downloaded on subsequent page loads.
- > Tree shaking: Next.js uses modern build tools like Webpack to remove unused code from your bundle, reducing its size.
- > Use webp images instead of jpeg/png: webp images sizes are less than jpeg/png and having same quality. You can use different tools which are use to covert images online. For Example:
1. Cloud Convert
2. Convertio
3. Tiny Img
By following these optimization techniques, you can significantly reduce the size of your Next.js JavaScript bundles and improve the performance of your application.