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; + })(); + ` + ); });