Next.js Discord

Discord Forum

Dynamic/Lazy import with CMS provided strings

Unanswered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
For a while I have been thinking about optimising icons that are selected by content-editors in a CMS in my Next projects.
Documentation on Dynamic imports or lazy loading imports state that imports must be defined and statically analysable, but some solutions to SO tickets state that work-arounds like concatenating the component/icon name to the path, does import dynamically on request, however, I can't seem to consistently get this to work.
Say I have a folder with icons icons/**.svg that are used sparingly, but semantically and content specific, what would be the most performant method of importing and rendering that component? An image request for an SVG is not a huge deal, but I would strongly prefer inlining my SVGs or even generating spritesheets for a page, since my routes are fairly static considering the long static lifetime of 9/10 pages that the client writes.
I have ran into this issue multiple times, and I have resorted to different solutions before, like huge icon fonts, serving the SVGs publicly and using them as images or simply predefining a limited icon set with their respective paths.
The one thing I think might solve this, is importing the context in a webpack loader so a reference to the large amount of icons is available at every render, however, my webpack skills leave something to be desired, especially in the context of the next.js environment. Therefore, I was looking to get a few opinions or experiences to see how others solve this seemingly trivial and common web problem in RSCs/Next.

4 Replies

Lee Robinson mentions SVG in his latest blog refresh post: https://leerob.io/blog/2023#opinions
he also links other interesting resources on the topic
trivial issues are usually the last to be solved in the web and the hardest so don't underestimate your problem, it's a super relevant question 🙂
Transvaal lionOP
Ah yes, I think I read this earlier this year. Wouldn't you think having SVG's inlined in SSG pages is a different beast though. But yea, after hydration it might pollute the bundle a bit. But never actually tried applying filters for changing their color on interaction.
PS: I agree with the triviality paradox on the web haha, good point 😜 I meant to say, trivial cause all I "actually" want to do is apply some "templating" logic, but in the end that's not really what happens of course