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'.
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(",")}`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With