'First Load JS shared by all is rather heavy in next.js
I have a project on Next.js framework and the problem is that First Load JS shared by all pages is rather heavy.
I want to know what possible aspects I can take into consideration to reduce it and also know if I'm doing something wrongly.
my next js version : ^10.0.3
information relating to pages while building :
Solution 1:[1]
I would suggest installing @next/bundle-analyzer
to get a better idea of what dependencies you're importing and which ones are contributing to that file size. This can help in identifying any unused or unnecessary libraries that could potentially be removed.
You can also look into using code splitting to reduce the bundle for the initial load of the application. This can be achieve by lazy loading code using dynamic import()
and/or next/dynamic
.
Furthermore, as mentioned in the Next.js documentation, there are other tools you can use to understand how much a dependency can add to your bundle.
(...) you can use the following tools to understand what is included inside each JavaScript bundle:
- Import Cost – Display the size of the imported package inside VSCode.
- Package Phobia – Find the cost of adding a new dev dependency to your project.
- Bundle Phobia - Analyze how much a dependency can increase bundle sizes.
Solution 2:[2]
As Answered Here
Question: How to reduce bundle size of first load page in Next.js? Answer
The newest iteration of Nextjs supports ES2020 dynamic import.
The syntax is a bit different from your traditional import statement, You shall import next/dynamic as
import dynamic from 'next/dynamic'
Now, with default export
const MyComponent= dynamic(() => import("../components/MyComponent"));
With named export
const MyNamedComponent= dynamic(() => import('../components/MyNamedComponent').then((mod) => mod.MyNamedFunction))
Now, you can use imported components similar to the normal components.
Moreover, you can also specify to show loading animation while the dynamic component loads up with passing { loading: () => <h2> Loading... </h2> }
as the second parameter to the dynamic()
function as,
const MyComponentWithLoading = dynamic(() => import('../components/ComponentWithLoading'),{ loading: () => <h2>Loading...</h2> })
You can find more here, Next.js Dynamic Import.
Hope that helped. Cheers!
Thank you.
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 | Ashok Chapagai |