From 8a1f818423fdeb3d347fbeff922824869101e4be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Kooi?= Date: Mon, 12 Sep 2016 14:46:36 +0200 Subject: [PATCH] don't merge block-scoped sibling vars across scopes, fix #153 --- .../transform-merge-sibling-variables-test.js | 29 +++++++++++++++++++ .../src/index.js | 9 ++++-- 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/babel-plugin-transform-merge-sibling-variables/__tests__/transform-merge-sibling-variables-test.js b/packages/babel-plugin-transform-merge-sibling-variables/__tests__/transform-merge-sibling-variables-test.js index 2895a2fe0..c06143888 100644 --- a/packages/babel-plugin-transform-merge-sibling-variables/__tests__/transform-merge-sibling-variables-test.js +++ b/packages/babel-plugin-transform-merge-sibling-variables/__tests__/transform-merge-sibling-variables-test.js @@ -36,4 +36,33 @@ describe("transform-merge-sibling-variables-plugin", () => { expect(transform(source).trim()).toBe(expected); }); + + it("don't concat block-scoped variables in for loops", () => { + const source = unpad(` + let i = 0; + for (let x = 0; x < 10; x++) console.log(i + x); + `); + const expected = unpad(` + let i = 0; + for (let x = 0; x < 10; x++) console.log(i + x); + `); + + expect(transform(source).trim()).toBe(expected); + }); + + it("concat block-scoped vars next to, but not into for loops", () => { + const source = unpad(` + let i = 0; + let y = 0; + for (let x = 0; x < 10; x++) console.log(i + x); + `); + const expected = unpad(` + let i = 0, + y = 0; + + for (let x = 0; x < 10; x++) console.log(i + x); + `); + + expect(transform(source).trim()).toBe(expected); + }); }); diff --git a/packages/babel-plugin-transform-merge-sibling-variables/src/index.js b/packages/babel-plugin-transform-merge-sibling-variables/src/index.js index 11e2ed3ce..f789f04f9 100644 --- a/packages/babel-plugin-transform-merge-sibling-variables/src/index.js +++ b/packages/babel-plugin-transform-merge-sibling-variables/src/index.js @@ -25,14 +25,19 @@ module.exports = function() { } }, - // concat variable declarations next to for loops with it's - // initialisers if they're of the same variable kind + // concat `var` declarations next to for loops with it's initialisers. + // block-scoped `let` and `const` are not moved because the for loop + // is a different block scope. function (path) { if (!path.inList) { return; } const { node } = path; + if (node.kind !== "var") { + return; + } + let next = path.getSibling(path.key + 1); if (!next.isForStatement()) { return;