diff --git a/packages/babel-plugin-transform-es2015-block-scoping/src/index.js b/packages/babel-plugin-transform-es2015-block-scoping/src/index.js index 6349483192..380c8972f2 100644 --- a/packages/babel-plugin-transform-es2015-block-scoping/src/index.js +++ b/packages/babel-plugin-transform-es2015-block-scoping/src/index.js @@ -435,16 +435,15 @@ class BlockScoping { let params = values(outsideRefs); let args = values(outsideRefs); - // build the closure that we're going to wrap the block with - let fn = t.functionExpression(null, params, t.blockStatement(block.body)); + const isSwitch = this.blockPath.isSwitchStatement(); + + // build the closure that we're going to wrap the block with, possible wrapping switch(){} + let fn = t.functionExpression(null, params, t.blockStatement(isSwitch ? [block] : block.body)); fn.shadow = true; // continuation this.addContinuations(fn); - // replace the current block body with the one we're going to build - block.body = this.body; - let ref = fn; if (this.loop) { @@ -473,6 +472,10 @@ class BlockScoping { } this.buildClosure(ret, call); + + // replace the current block body with the one we're going to build + if (isSwitch) this.blockPath.replaceWithMultiple(this.body); + else block.body = this.body; } /** diff --git a/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/actual.js b/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/actual.js new file mode 100644 index 0000000000..c57bdc6e51 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/actual.js @@ -0,0 +1,10 @@ +function fn() { + switch (true) { + default: + let foo = 4; + if (true) { + let bar = () => foo; + console.log(bar()); + } + } +} diff --git a/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/expected.js b/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/expected.js new file mode 100644 index 0000000000..2efd145af3 --- /dev/null +++ b/packages/babel-plugin-transform-es2015-block-scoping/test/fixtures/general/switch-callbacks/expected.js @@ -0,0 +1,14 @@ +function fn() { + (function () { + switch (true) { + default: + var foo = 4; + if (true) { + var bar = function () { + return foo; + }; + console.log(bar()); + } + } + })(); +}