From 4ddb158c727db980fe1aedcbea7103679dbaf733 Mon Sep 17 00:00:00 2001 From: Tadeu Zagallo Date: Tue, 17 Nov 2015 11:10:35 -0800 Subject: [PATCH] Add ternary elimination support to the WPO pass Summary: public Replaces ``` __DEV__ ? foo() : bar() ``` with ``` bar() ``` for non-dev builds. Reviewed By: davidaurelio Differential Revision: D2663838 fb-gh-sync-id: 30fdfa72dda89fc0d340da359e0f43db2917fcf5 --- .../__tests__/dead-module-elimination-test.js | 9 +++++ .../dead-module-elimination.js | 37 ++++++++++++------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/react-packager/src/transforms/whole-program-optimisations/__tests__/dead-module-elimination-test.js b/react-packager/src/transforms/whole-program-optimisations/__tests__/dead-module-elimination-test.js index 089f8695..7525fd0f 100644 --- a/react-packager/src/transforms/whole-program-optimisations/__tests__/dead-module-elimination-test.js +++ b/react-packager/src/transforms/whole-program-optimisations/__tests__/dead-module-elimination-test.js @@ -103,4 +103,13 @@ describe('dead-module-elimination', () => { require('bar');` ); }); + + it('should replace falsy ternaries with alternate expression', () => { + compare( + `__DEV__ = false; + __DEV__ ? foo() : bar(); + `, + `bar();` + ); + }); }); diff --git a/react-packager/src/transforms/whole-program-optimisations/dead-module-elimination.js b/react-packager/src/transforms/whole-program-optimisations/dead-module-elimination.js index 82e9b5da..39eeb0a6 100644 --- a/react-packager/src/transforms/whole-program-optimisations/dead-module-elimination.js +++ b/react-packager/src/transforms/whole-program-optimisations/dead-module-elimination.js @@ -33,6 +33,28 @@ function CallExpression(path) { } } +function IfStatement(path) { + const { node } = path; + + if (node.test.type === 'Identifier' && node.test.name in globals) { + if (globals[node.test.name]) { + if (node.consequent.type === 'BlockStatement') { + path.replaceWithMultiple(node.consequent.body); + } else { + path.replaceWith(node.consequent); + } + } else if (node.alternate) { + if (node.alternate.type === 'BlockStatement') { + path.replaceWithMultiple(node.alternate.body); + } else { + path.replaceWith(node.alternate); + } + } else { + path.remove(); + } + } + } + module.exports = function () { var firstPass = { AssignmentExpression(path) { @@ -60,19 +82,8 @@ module.exports = function () { //scope.removeBinding(node.left.name); } }, - IfStatement(path) { - const { node } = path; - - if (node.test.type === 'Identifier' && node.test.name in globals) { - if (globals[node.test.name]) { - path.replaceWithMultiple(node.consequent.body); - } else if (node.alternate) { - path.replaceWithMultiple(node.alternate.body); - } else { - path.remove(); - } - } - }, + IfStatement, + ConditionalExpression: IfStatement, Identifier(path) { const { node } = path;