Reputation: 9768
I need to dynamically define classes so have written a code generator in my ES6 code:
function makeClass(className, baseClass = _DefaultBaseClass, ...args) {
return (
eval(`
class ${className} extends ${baseClass} {
constructor(${...args}) {
super(${...args})
}
}
`)
)
}
'_DefaultBaseClass' is an empty class used to simplify the above generator function logic:
class _DefaultBaseClass() {
constructor() {}
}
Everything works fine with the generator code, except for the spread operator. The spread operator itself works fine in my project outside of the template literal in this example.
I'm using the following webpack Babel presets/plugins: 'react', 'es2015', 'stage-2', 'transform-runtime'.
Upvotes: 15
Views: 5996
Reputation: 26848
As mentioned in the comments ...
is bound to specific use cases. ${...args}
wouldn't even make much sense. What should be the result? E.g. if ${...args}
would be equivalent to ${args[0],args[1]}
, then it would evaluate to the value of args[1]
, because here ,
is a comma operator.
Template literals can contain arbitrary expressions, so you can do the following:
`${args.join(",")}`
Upvotes: 16