Dynamically create instances of Exported classes via webpack

250 Views Asked by At

I have an component based system where components are es6 classes exported via webpack.

export default ClassName {}

import ClassName from "classname.js"

This all works and i automated this.

Now for the next part i need to automatically create an instance of this imported class like this: (pseudocode)

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

I cannot do this because c as in "ClassName" is not defined. When i lookup the compiled js by webpack i see it imported my class as _ClassName. So i tried to prepend a _ but still mo result.

Has anyone experience with auto instanciating classes with webpack?

1

There are 1 best solutions below

0
Robin Crama On BEST ANSWER

The above comments solved the issue.

For anyone who is interested, this is the auto generated file now:

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