From 552766955c011618f86c0f39451b9e288383c67a Mon Sep 17 00:00:00 2001 From: Vignesh Shanmugam Date: Tue, 1 May 2018 19:40:46 +0200 Subject: [PATCH] fix(merge-sibling-var): recalculate dedeclaratios when concatenating variables (#826) --- .../src/index.js | 16 ++++++++++--- .../__tests__/minify-env-tests.js | 23 +++++++++++++++++++ 2 files changed, 36 insertions(+), 3 deletions(-) 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 ba69d2511..968b248f1 100644 --- a/packages/babel-plugin-transform-merge-sibling-variables/src/index.js +++ b/packages/babel-plugin-transform-merge-sibling-variables/src/index.js @@ -57,14 +57,24 @@ module.exports = function({ types: t }) { let sibling = path.getSibling(path.key + 1); + let declarations = []; + while (sibling.isVariableDeclaration({ kind: node.kind })) { - node.declarations = node.declarations.concat( - sibling.node.declarations - ); + declarations = declarations.concat(sibling.node.declarations); + sibling.remove(); sibling = path.getSibling(path.key + 1); } + + if (declarations.length > 0) { + path.replaceWith( + t.variableDeclaration(node.kind, [ + ...node.declarations, + ...declarations + ]) + ); + } }, // concat `var` declarations next to for loops with it's initialisers. diff --git a/packages/babel-preset-minify/__tests__/minify-env-tests.js b/packages/babel-preset-minify/__tests__/minify-env-tests.js index 8f1f5a24e..20575215e 100644 --- a/packages/babel-preset-minify/__tests__/minify-env-tests.js +++ b/packages/babel-preset-minify/__tests__/minify-env-tests.js @@ -158,4 +158,27 @@ describe("preset along with env", () => { } ` ); + + thePlugin( + "should fix issue#825-merge-sibling-vars", + ` + (function() { + const blah = 71; + + var start = 1, navx = ''; + while (start < 71) { + navx += 'a'; + start += 10; + } + return 'b' + navx; + })(); + `, + ` + (function () { + for (var a = 1, b = ''; 71 > a;) b += 'a', a += 10; + + return 'b' + b; + })(); + ` + ); });