Next.js Discord

Discord Forum

Dynamic Import still imports the whole library

Common Murre posted this in #help-forum
Open in Discord
Common MurreOP
Hi, I'm trying to integrate Strapi to Next and want to make Icon (MUI's Icon Material) be mapped and editable via Strapi. So, I found Dynamic Import in Next JS Docs and implement it like on the picture. I ran dev and node ram usage spikes to 8GBs. Did I do it wrong? or is there any trick in implementing this?

6 Replies

Holland Lop
The code you provided doesn't have any problem, the problem might be in using this Method on infinite loop or something similar
Southern rough shrimp
Is it not because every time you call this component, you're dynamically importing the component
try moving those imports outside of the function
This is the nextjs example, they define the const outside of the function scope.
The issue is that you're using the variable in the import name. I can't remember where in the docs it says that, but that will always default to the entire library because it's not known at build time. Instead of the dynamic import for that component, just use an async function like const MyComponent = async () => await import(./pathToComponent/${someVar})
Common MurreOP
Hi @Tonkinese @Holland Lop @Southern rough shrimp!

Thank you for your respond I appreciate it and Im sorry for my rate reply.

Firstly I do believe that it’s true, since the path variable is empty on compilation time, it would import everything in that library. I tried changing the whole import path from a variable and it always errors out.

Secondly, the codes @Southern rough shrimp gave will work. But it doesn’t do what I’m trying to do.

So here’s what I’m trying to do.
I want to be able to dynamically select material icons from strapi cms. This means getting string as input and then import the selected icon.

Mapping all of the icons means importing the whole icons right? Since there’s 2000+ icons in the library, importing them all eats a lot of ram.

Do you guys have any suggestions on this?