Search code examples
javascriptstenciljs

How to dynamically import an object exported from another file?


In my node_modules, I have a folder with an index.js which exports an object which contains a bunch of icon objects.

export { arrow1, arrow2, arrow3 .. }

I want to somehow dynamically import an icon object from another component. I am using Stencil.js, which is similar to React, and I need to use the icon string passed as a prop to dynamically import that particular icon object. How do I do that? The issue is that the import statement must be at the top of the page, but the prop is defined below.

Is there a way to import an exported object without using the import statement? I tried with fetch() but it wasn't working. It kept returning status not ok.


Solution

  • I don't see point how importing all icons is a performance issue. Here is small example, but it depends on what format are the imported icons.

    import { IconNames } from '../icon/types';
    
    @Component({
      tag: 'custom-component'
    })
    export class CustomComponent {
       @Prop() iconName: keyof IconNames;
       
       render() {
        const unicodeIcon = String.fromCharCode(parseInt(getIconHexCharCode(this.iconName), 16));
        return (
          <span>{unicodeIcon}</span>
        )
       }
    }