I use babel.js traspiler to write ES6 code.
I have a string containing class name. I want a class that I can instantiate. How?
I tried:
eval("MyClassName") -> :(
window["MyClassName"] -> :(
Any ideas?
I use babel.js traspiler to write ES6 code.
I have a string containing class name. I want a class that I can instantiate. How?
I tried:
eval("MyClassName") -> :(
window["MyClassName"] -> :(
Any ideas?
You Can:
Since with BabelJS you have to transpile to an ES5 module loader, it would be as simple as (depending on the module format you've specified at transpile time):
const MyClassName = require("MyClassName");
const obj = new MyClassName();
However this is not ES6, but transpiled ES5. So your code will not work in true ES6 environments.
In an ES6 environment a class
is just syntactic sugar for a function, so there is no reason you cannot do:
// Class definition
class MyClassName { }
// Pollute global scope
(global || window).MyClassName = MyClassName;
And load it like so:
const instance = new (window || global)["MyClassName"]();
But in doing so you've just broken the major feature modules give you in the first place.
You Should:
Create a factory class. In the majority of cases, the amount of classes you can instantiate is finite. You should create a factory function which gives you a class instance based on a string:
import MyClassName from "./MyClassName"
class MyFactory {
static getInstance(value) {
if(value === "MyClassName") {
return new MyClassName();
}
throw new Error(`Could not instantiate ${value}`);
}
}
Which would be used as:
import MyFactory from "./MyFactory";
const instance = MyFactory.getInstance("MyClassName");
Obviously you could expand on that to use a Map
instead of a string of if
statements, but you get the idea.