From a815a4955beac675f0aadc050f840c57b80c659a Mon Sep 17 00:00:00 2001 From: MO Date: Mon, 16 May 2022 00:47:18 +0800 Subject: [PATCH] fix: cannot remove var declaration after return --- lib/index.js | 35 +++++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/lib/index.js b/lib/index.js index c9d5f55..6218eb0 100644 --- a/lib/index.js +++ b/lib/index.js @@ -560,16 +560,18 @@ module.exports = function (_ref) { var paths = path.get("body"); var purge = false; + var completionPath = null; for (var i = 0; i < paths.length; i++) { var p = paths[i]; if (!purge && p.isCompletionStatement()) { purge = true; + completionPath = p; continue; } - if (purge && !canExistAfterCompletion(p)) { + if (purge && (!canExistAfterCompletion(p) || canSafelyRemoved(p, completionPath))) { removeOrVoid(p); } } @@ -1387,6 +1389,35 @@ module.exports = function (_ref) { function canExistAfterCompletion(path) { return path.isFunctionDeclaration() || path.isVariableDeclaration({ kind: "var" }); } + + function canSafelyRemoved(path, completionPath) { + if ( + completionPath && + path.isVariableDeclaration({ kind: 'var' }) && + completionPath.isReturnStatement() + ) { + var completionEnd = completionPath.node.end; + + return path.node.declarations.every(function (decl) { + var name = decl.id.name || ''; + var binding = path.scope.getBinding(name); + + if (!binding) { + return false; + } + + if (binding.referencePaths.length === 0) { + return true; + } + + return binding.referencePaths.every(function (refPath) { + return refPath.node.start > completionEnd; + }); + }); + } + + return false; + } function getLabel(name, _path) { var label = void 0, @@ -1420,4 +1451,4 @@ module.exports = function (_ref) { } return t.sequenceExpression(result); } -}; \ No newline at end of file +};