How to reduce bundle size of first load page in Next.js? [duplicate]
Asked Answered
G

1

6

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

Gonroff answered 10/6, 2020 at 18:39 Comment(8)
What have you tried so far? One thing to look into may be dynamic component loading.Girgenti
I removed some images, checking the external libraries that I use. But that's no problem, cus I am using the same libraries on all pages and you can see differences between the statistics page and the rest of the pages. I have a lot of features on statistics page that's problem 99%Gonroff
@Girgenti I found which component is problem, it's correct, that component is dynamically rendered. Do you know some way how to fix that?Gonroff
Which component is it?Girgenti
The size of the statistics page without the shared js is 371kB, which makes me suspect either there is some component with an enormous amount of code or includes some external client-side library which is not lazy-loaded. There might also be an issue with the tree shaking.Intrados
@MarkJames try analyzing the wepack bundle for your app, This example in nextjs repo might help.Intrados
Did you try with dynamic imports or lazy loading your components on this page?Weariless
so tldr is use dynamic import instead of normal import right guys?Shape
G
3

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.

Gradation answered 4/5, 2022 at 11:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.