Vite, Elastic UI: Failing to dynamically import icons for EuiIcon

471 Views Asked by At

https://github.com/rorymcd98/spot-the-image-gen

Here's my repo. To install simply do:

yarn install

yarn dev

The issue that I'm having is with Elastic UI's EuiIcon in the ./src/components/Counters.tsx. I'm trying to import shard and bullseye type icons.

Problem: As you can see, in the current version they are not rendering. In the dev server I'm getting an error:

caught (in promise) TypeError: Failed to fetch dynamically imported module: http://localhost:5174/node_modules/.vite/deps/assets/bullseye?import

I've tried quite a few things, but based on the documentation I can't tell where I'm going wrong. I have tried creating a public/assets/{name}.svg file for each but this didn't appear to work.

Could someone take a brief look at my repo and see where I'm going wrong? Thanks.

2

There are 2 best solutions below

0
On

Since @kurupt_89's answer is for JavaScript, I post the following as a complement for TypeScript.

  1. Import the whole set of icons using this file.

  2. Or only import the icons you want by adding a file containing codes similar to the following to your project:

    import { ICON_TYPES } from "@elastic/eui";
    import { appendIconComponentCache } from "@elastic/eui/es/components/icon/icon";
    
    // Suppose you want to use the "exit" icon
    import { icon as exit } from "@elastic/eui/es/components/icon/assets/exit";
    
    type IconComponentNameType = (typeof ICON_TYPES)[0];
    type IconComponentCacheType = Partial<Record<IconComponentNameType, unknown>>;
    
    const cachedIcons: IconComponentCacheType = {
      exit,
    };
    
    appendIconComponentCache(cachedIcons);
    
  3. Create a global.d.ts file containing the following code to suppress TypeScript's error:

    declare module "@elastic/eui/es/components/icon/*";
    

For more information you can check this issue.

0
On

Did some quick research on this. Found the solution in the wiki.

Just import the icons and pass them to the function appendIconComponentCache.

import { appendIconComponentCache } from '@elastic/eui/es/components/icon/icon';

import { icon as EuiIconArrowDown } from '@elastic/eui/es/components/icon/assets/arrow_down';
import { icon as EuiIconArrowLeft } from '@elastic/eui/es/components/icon/assets/arrow_left';

// One or more icons are passed in as an object of iconKey (string): IconComponent
appendIconComponentCache({
  arrowDown: EuiIconArrowDown,
  arrowLeft: EuiIconArrowLeft,
});

https://github.com/elastic/eui/tree/main/wiki/consuming-eui#failing-icon-imports