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

时间:2018-08-17 15:52:01

标签: class webpack ecmascript-6 babel instances

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

export default ClassName {}

import ClassName from "classname.js"

这一切正常,我将其自动化。

现在,对于下一部分,我需要自动创建此导入类的实例,如下所示:(伪代码)

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

我无法执行此操作,因为未定义“ ClassName”中的c。当我通过webpack查找编译的js时,我看到它将我的类导入为_ClassName。因此,我尝试添加一个_,但仍然会保留结果。

有人使用webpack进行自动实例化课程吗?

1 个答案:

答案 0 :(得分:0)

以上评论解决了这个问题。

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

/* 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));
        }
    }
});