Skip to content

Dynamically importing icons using Vite 5> #662

Open
@balboFK

Description

@balboFK

I was trying to achieve dynamic imports with the goal of reducing bundle size, since the project itself is quite heavy when fully bundled. But i ended up having problemns to figure out what should be the correct approach to avoid a full bundle request.

My approach was to create a functional component that was going to received the icon name as a target and try to "lazy" import.
As follows:

import { CaretRightOutlined } from '@ant-design/icons'
import { lazy, Suspense } from 'react'

type Props = {
  iconName: string
}

export function IconFC ({ iconName }: Props): JSX.Element {
  const AntdIcon = lazy(async () => import(
    `@ant-design/icons/${iconName}`
  ).then(module => ({ default: module.default })))

  return (
    <Suspense fallback={<CaretRightOutlined />}>
      <AntdIcon />
    </Suspense>
  )
}

But i get an error on Vite end:
image

And an error on the browsers end:
image

By looking at the folder structure at @ant-design/icons this approach looks like it should work:

image

Also the error on the browser is from an icon that i didnt try to use.

Any ideas on what could be done? My goal is to reduce bundle size since i use a great number of icons, but not all of them.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions