diff --git a/src/babel/transformation/transformers/es6/template-literals.js b/src/babel/transformation/transformers/es6/template-literals.js index 9c65385f43..5c770f7216 100644 --- a/src/babel/transformation/transformers/es6/template-literals.js +++ b/src/babel/transformation/transformers/es6/template-literals.js @@ -45,6 +45,10 @@ export function TaggedTemplateExpression(node, parent, scope, file) { return t.callExpression(node.tag, args); } +function isString(node) { + return t.isLiteral(node) && typeof node.value === "string"; +} + export function TemplateLiteral(node, parent, scope, file) { var nodes = []; @@ -56,9 +60,18 @@ export function TemplateLiteral(node, parent, scope, file) { } if (nodes.length > 1) { - // remove redundant '' at the end of the expression - var last = nodes[nodes.length - 1]; - if (t.isLiteral(last, { value: "" })) nodes.pop(); + // filter out empty string literals + nodes = nodes.filter(n => !t.isLiteral(n, { value: "" })); + + if (nodes.length === 1 && isString(nodes[0])) { + return nodes[0]; + } + + // since `+` is left-to-right associative + // ensure the first node is a string if first/second isn't + if (!isString(nodes[0]) && !isString(nodes[1])) { + nodes.unshift(t.literal("")); + } var root = buildBinaryExpression(nodes.shift(), nodes.shift()); diff --git a/test/core/fixtures/transformation/es6.template-literals/expression-first/actual.js b/test/core/fixtures/transformation/es6.template-literals/expression-first/actual.js new file mode 100644 index 0000000000..ee6e49ef50 --- /dev/null +++ b/test/core/fixtures/transformation/es6.template-literals/expression-first/actual.js @@ -0,0 +1,8 @@ +const foo = 5; +const bar = 10; +const baz = 15; + +const example = `${"a"}`; +const example2 = `${1}`; +const example3 = 1 + `${foo}${bar}${baz}`; +const example4 = 1 + `${foo}bar${baz}`; diff --git a/test/core/fixtures/transformation/es6.template-literals/expression-first/expected.js b/test/core/fixtures/transformation/es6.template-literals/expression-first/expected.js new file mode 100644 index 0000000000..5185926b93 --- /dev/null +++ b/test/core/fixtures/transformation/es6.template-literals/expression-first/expected.js @@ -0,0 +1,10 @@ +"use strict"; + +var foo = 5; +var bar = 10; +var baz = 15; + +var example = "a"; +var example2 = "" + 1; +var example3 = 1 + ("" + foo + bar + baz); +var example4 = 1 + (foo + "bar" + baz);