如何动态导入从另一个文件导出的对象?

huangapple go评论65阅读模式
英文:

How to dynamically import an object exported from another file?

问题

在我的 node_modules 中,我有一个包含许多图标对象的文件夹,其中包含一个名为 index.js 的文件,它导出了一个对象。

export { arrow1, arrow2, arrow3 .. }

我想要以某种方式从另一个组件动态导入一个图标对象。我正在使用类似于React的Stencil.js,并且需要使用作为属性传递的图标字符串来动态导入特定的图标对象。我该如何实现这一点?问题在于导入语句必须位于页面顶部,但属性在下面定义。

有没有一种方法可以在不使用导入语句的情况下导入导出的对象?
我尝试使用 fetch(),但它不起作用。它一直返回 status not ok

英文:

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.

答案1

得分: 0

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>
    )
   }
}
英文:

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.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { IconNames } from &#39;../icon/types&#39;;

@Component({
  tag: &#39;custom-component&#39;
})
export class CustomComponent {
   @Prop() iconName: keyof IconNames;
   
   render() {
    const unicodeIcon = String.fromCharCode(parseInt(getIconHexCharCode(this.iconName), 16));
    return (
      &lt;span&gt;{unicodeIcon}&lt;/span&gt;
    )
   }
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月6日 22:11:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75362426.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定