通过 webpack 动态创建 Exported 类 的实例

Dynamically create instances of Exported classes via webpack

我有一个基于组件的系统,其中组件是通过 webpack 导出的 es6 classes。

export default ClassName {}

import ClassName from "classname.js"

一切正常,我自动完成了。

现在,对于下一部分,我需要像这样自动创建这个导入的 class 的实例:(伪代码)

//components is an array of strings with all the classnames.
for(var c in components) {
    eval("new "+c+"()");
}

我不能这样做,因为 "ClassName" 中的 c 没有定义。当我通过 webpack 查找已编译的 js 时,我看到它将我的 class 导入为 _ClassName。所以我试着在前面加上一个 _ 但结果仍然没有。

有人使用 webpack 自动实例化 classes 吗?

以上评论解决了问题。

对于任何感兴趣的人,这是现在自动生成的文件:

/* this file is auto-generated.  DO NOT MODIFY*/
import BreakpointTool from '../../Components/BreakpointTool/scripts/BreakpointTool.js';
import ComponentA from '../../Components/componentA/scripts/componentA.js';
import FoundationMenu from '../../Components/FoundationMenu/scripts/FoundationMenu.js';
import Slider from '../../Components/Slider/scripts/Slider.js';

var componentIncludes = [
        BreakpointTool,
        ComponentA,
        FoundationMenu,
        Slider
    ];

var componentsList = [
        "BreakpointTool",
        "ComponentA",
        "FoundationMenu",
        "Slider"
    ];

var components;

function getComponentObjectByName(name) {
    var index = componentsList.indexOf(name);

    if (index == -1) {
        return null;
    }

    return componentIncludes[index];
}

$(function () {
    components = new Map();

    for (var c of componentsList) {
        var $component = $("." + c);

        if ($component.length > 0) {
            $component.each(function (i, elm) {
                var componentName = this;
                var componentId = componentName + "_" + i;

                var componentObject = getComponentObjectByName(componentName);
                var component = new componentObject(elm, componentId);

                components.set(componentId, component);
            }.bind(c));
        }
    }
});