I am trying to create an Icon component in a Next.js application that imports SVGs dynamically without significantly increasing the bundle size. Despite using various methods such as require.context(), dynamic(), and await import(), I am encountering an issue where all SVGs are being imported, resulting in a large bundle size.
Link to the code that reproduces this issue:
GitHub Repository
Steps to Reproduce:
Clone the repository and read the README.md.
Review and modify the page.tsx as directed in the readme.
Build the application.
Examine the bundle size.
Current vs. Expected Behavior:
Current: When importing a single SVG, all SVGs are imported, causing a significant increase in the bundle size.
Expected: Only the imported SVG should be included in the bundle, keeping the bundle size minimal.
Environment Information:
Operating System:
Platform: win32
Arch: x64
Version: Windows 10 Enterprise
Available memory (MB): 14274
Available CPU cores: 8
Binaries:
Node: 18.17.0
npm: N/A
Yarn: N/A
pnpm: N/A
Relevant Packages:
next: 14.2.3 (There is a newer version 14.2.4 available, upgrade recommended!)
eslint-config-next: 14.2.3
react: 18.3.1
react-dom: 18.3.1
typescript: 5.4.5
Next.js Config:
Output: N/A
Note: There is a newer version (14.2.4) available, upgrade recommended. Please try the latest canary version (npm install next@canary) to confirm the issue still exists before creating a new issue. More info here.
Affected Areas:
create-next-app
Lazy Loading
Performance
Webpack
Affected Stages:
next build (local)
Additional Context:
I am attempting to dynamically import SVGs into an Icon component without significantly increasing the bundle size. I’ve explored various solutions available online such as require.context(), dynamic(), await import(), etc. However, all these methods result in a large bundle size as they import all SVGs. One solution avoids this issue by loading the SVGs on the client side, but this causes the SVGs to appear after a delay.
I do not understand why importing a single SVG causes all SVGs to be included in the bundle. Ideally, Next.js should split them into chunks.
The repository with different solutions can be found here.