diff --git a/packages/babel-plugin-transform-destructuring/src/index.js b/packages/babel-plugin-transform-destructuring/src/index.js index 814ff169ee92..7af938dbeb28 100644 --- a/packages/babel-plugin-transform-destructuring/src/index.js +++ b/packages/babel-plugin-transform-destructuring/src/index.js @@ -190,7 +190,7 @@ export default declare((api, options) => { const keys = []; let allLiteral = true; - + let hasTemplateLiteral = false; for (let i = 0; i < pattern.properties.length; i++) { const prop = pattern.properties[i]; @@ -204,8 +204,9 @@ export default declare((api, options) => { const key = prop.key; if (t.isIdentifier(key) && !prop.computed) { keys.push(t.stringLiteral(key.name)); - } else if (t.isTemplateLiteral(prop.key)) { - keys.push(t.cloneNode(prop.key)); + } else if (t.isTemplateLiteral(key)) { + keys.push(t.cloneNode(key)); + hasTemplateLiteral = true; } else if (t.isLiteral(key)) { keys.push(t.stringLiteral(String(key.value))); } else { @@ -228,7 +229,7 @@ export default declare((api, options) => { t.memberExpression(keyExpression, t.identifier("map")), [this.addHelper("toPropertyKey")], ); - } else if (!t.isProgram(this.scope.block)) { + } else if (!hasTemplateLiteral && !t.isProgram(this.scope.block)) { // Hoist definition of excluded keys, so that it's not created each time. const program = this.scope.path.findParent(path => path.isProgram()); const id = this.scope.generateUidIdentifier("excluded"); diff --git a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/input.js b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/input.js new file mode 100644 index 000000000000..bf5b80eb1bee --- /dev/null +++ b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/input.js @@ -0,0 +1,4 @@ +const example = (obj) => { + const foo = 'foo'; + const { [`prefix_${foo}`]: _, ...rest } = obj; +}; diff --git a/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/output.js b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/output.js new file mode 100644 index 000000000000..000d34966b47 --- /dev/null +++ b/packages/babel-plugin-transform-destructuring/test/fixtures/destructuring/check-no-hoisting-when-using-template-strings/output.js @@ -0,0 +1,5 @@ +var example = obj => { + var foo = 'foo'; + var _ = obj[`prefix_${foo}`], + rest = babelHelpers.objectWithoutProperties(obj, [`prefix_${foo}`]); +};