Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reduce bundle size of first load page in Next.js?

I have a very big bundle size of one of my pages.

How can I improve the first loading of the page in Next.js?

Pls take a look on screenshot:

enter image description here

like image 210
Mark James Avatar asked Jun 10 '20 18:06

Mark James


People also ask

What is first load js in NextJS?

The first load is colored green, yellow, or red. Aim for green for performant applications. When you use Next CLI, this little bit of feedback on its own is immensely valueable for monitoring your own bundle size. Every time you build your application, the NextJS CLI outputs your First Load JS for each of your pages.


Video Answer


1 Answers

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.

like image 140
Ashok Chapagai Avatar answered Oct 18 '22 23:10

Ashok Chapagai