英文:
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 '../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>
)
}
}
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论