From 905bf49df884a598bb2ad1a965023efbcfd6dd19 Mon Sep 17 00:00:00 2001 From: Boopathi Rajaa Date: Sat, 8 Jul 2017 15:52:36 +0200 Subject: [PATCH] [DCE] Fix removal of ArrayPattern + (Fix 617) --- .../__tests__/dead-code-elimination-test.js | 22 +++++++++++++ .../src/index.js | 32 ++++++++++++------- 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js b/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js index cb42baadd..3e4476b64 100644 --- a/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js +++ b/packages/babel-plugin-minify-dead-code-elimination/__tests__/dead-code-elimination-test.js @@ -2426,4 +2426,26 @@ describe("dce-plugin", () => { } ` ); + + thePlugin( + "should bail out for Array and Object Pattern - fix issue#617", + ` + function foo(arr) { + let [a, b] = arr; + console.log(a); + } + ` + ); + + thePlugin( + "should bail out for Array and Object Pattern - fix issue#617", + ` + function foo() { + return getPromise().then(arr => { + let { a, b } = arr; + console.log(a); + }); + } + ` + ); }); diff --git a/packages/babel-plugin-minify-dead-code-elimination/src/index.js b/packages/babel-plugin-minify-dead-code-elimination/src/index.js index b030a9330..09fc01158 100644 --- a/packages/babel-plugin-minify-dead-code-elimination/src/index.js +++ b/packages/babel-plugin-minify-dead-code-elimination/src/index.js @@ -228,21 +228,29 @@ module.exports = ({ types: t, traverse }) => { continue; } - if ( - binding.path.isVariableDeclarator() && - binding.path.node.init && - !scope.isPure(binding.path.node.init) && - binding.path.parentPath.node.declarations - ) { - if (binding.path.parentPath.node.declarations.length !== 1) { - continue; - } - // Bail out for ArrayPattern and ObjectPattern + if (binding.path.isVariableDeclarator()) { if (!binding.path.get("id").isIdentifier()) { + // deopt for object and array pattern continue; } - binding.path.parentPath.replaceWith(binding.path.node.init); + // if declarator has some impure init expression + // var x = foo(); + // => foo(); + if ( + binding.path.node.init && + !scope.isPure(binding.path.node.init) && + binding.path.parentPath.node.declarations + ) { + // binding path has more than one declarations + if (binding.path.parentPath.node.declarations.length !== 1) { + continue; + } + binding.path.parentPath.replaceWith(binding.path.node.init); + } else { + updateReferences(binding.path, this); + removeOrVoid(binding.path); + } } else { updateReferences(binding.path, this); removeOrVoid(binding.path); @@ -403,7 +411,7 @@ module.exports = ({ types: t, traverse }) => { } } } - } + } // end-for-of } },