diff --git a/src/scope-hoisting/hoist.js b/src/scope-hoisting/hoist.js index c871e0a7bc6..199d8c0c77b 100644 --- a/src/scope-hoisting/hoist.js +++ b/src/scope-hoisting/hoist.js @@ -156,8 +156,6 @@ module.exports = { scope.push({id: exportsIdentifier, init: t.objectExpression([])}); } - let topDecls = []; - // Move all "var" variables to the top-level to prevent out of order definitions when wrapped. for (let name in scope.bindings) { let binding = scope.getBinding(name); @@ -166,35 +164,26 @@ module.exports = { let {parentPath} = binding.path; if (!parentPath.removed) { - let {declarations} = parentPath.node; - - if (declarations.length) { - parentPath.insertBefore( - declarations - .map( - decl => - decl.init - ? t.assignmentExpression('=', decl.id, decl.init) - : null - ) + if (parentPath.node.declarations.length) { + binding.path.getStatementParent().insertBefore( + parentPath.node.declarations + .map(decl => { + binding.scope.removeBinding(decl.id.name); + scope.push({id: decl.id}); + + return decl.init + ? t.assignmentExpression('=', decl.id, decl.init) + : null; + }) .filter(decl => decl !== null) ); - - topDecls.push( - ...declarations.map(decl => t.variableDeclarator(decl.id)) - ); - parentPath.remove(); } - } else if (!binding.path.removed) { - binding.path.remove(); + + parentPath.remove(); } - } - } - if (topDecls.length) { - path.unshiftContainer('body', [ - t.variableDeclaration('var', topDecls) - ]); + binding.path.remove(); + } } } diff --git a/test/integration/scope-hoisting/commonjs/hoist-vars/b.js b/test/integration/scope-hoisting/commonjs/hoist-vars/b.js index 49ef995325f..0bc4fb6d40a 100644 --- a/test/integration/scope-hoisting/commonjs/hoist-vars/b.js +++ b/test/integration/scope-hoisting/commonjs/hoist-vars/b.js @@ -1,3 +1,13 @@ if(process.env.NODE_ENV === 'test') { - module.exports = require('./c') + var c = require('./c')() + + for(var i = 0, {length} = c, out = ''; i < length; i++) { + out += c[i] + } + + module.exports = function() { + if(c != out) throw new Error() + + return out + } }