Reputation: 353
Why babel convert string interpolation into concat?
if I have this code:
const to = "Cflower";
const from = "your script";
console.log(`Hello, ${to}! Greeting from ${from}`);
Babel compiles to:
var to = "Cflower";
var from = "your script";
console.log("Hello, ".concat(to, "! Greeting from ").concat(from));
TypeScript do the same thing. But the problem is, concat is slower than "+", MDN suggest to use "+" instant of concat, and also "+" string concat is available in es5, then why babel do that? Are there any purpose?
And I'm writing an app, performance is important, can I let babel generate "+" instead of concat for me?
Upvotes: 2
Views: 353
Reputation: 38982
Earlier, Babel transpiled template literal expression and quasis with a +
after converting them to strings. As a result, Symbols in template strings didn't throw an error.
This handling wasn't compatible with the specification so they changed the implementation to use concat.
Since then, the transpiled output doesn't perform explicit conversion of the template literal expressions and quasis to strings when using the +
operator.
If you are on Babel 7.13.0 or higher, set the mutableTemplateObject
in at the top level in your configuration to true
.
{
"assumptions": {
"mutableTemplateObject": true
},
...
}
Otherwise, set the loose option for @babel/plugin-transform-template-literals
to true
to have the strings in template literal combined with the +
operator.
"plugins": [
[
"@babel/plugin-transform-template-literals",
{
"loose": true
}
]
]
Upvotes: 2