Skip to content

Commit 90ae8af

Browse files
authored
fix: avoid empty block for unused statement
1 parent 8db97f8 commit 90ae8af

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

lib/ConstPlugin.js

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ class ConstPlugin {
180180
? statement.alternate
181181
: statement.consequent;
182182
if (branchToRemove) {
183-
this.eliminateUnusedStatement(parser, branchToRemove);
183+
this.eliminateUnusedStatement(parser, branchToRemove, true);
184184
}
185185
return bool;
186186
}
@@ -193,7 +193,7 @@ class ConstPlugin {
193193
) {
194194
return;
195195
}
196-
this.eliminateUnusedStatement(parser, statement);
196+
this.eliminateUnusedStatement(parser, statement, false);
197197
return true;
198198
});
199199
parser.hooks.expressionConditionalOperator.tap(
@@ -509,9 +509,10 @@ class ConstPlugin {
509509
* Eliminate an unused statement.
510510
* @param {JavascriptParser} parser the parser
511511
* @param {Statement} statement the statement to remove
512+
* @param {boolean} alwaysInBlock whether to always generate curly brackets
512513
* @returns {void}
513514
*/
514-
eliminateUnusedStatement(parser, statement) {
515+
eliminateUnusedStatement(parser, statement, alwaysInBlock) {
515516
// Before removing the unused branch, the hoisted declarations
516517
// must be collected.
517518
//
@@ -545,8 +546,14 @@ class ConstPlugin {
545546
const declarations = parser.scope.isStrict
546547
? getHoistedDeclarations(statement, false)
547548
: getHoistedDeclarations(statement, true);
548-
const replacement =
549-
declarations.length > 0 ? `{ var ${declarations.join(", ")}; }` : "{}";
549+
550+
const inBlock = alwaysInBlock || statement.type === "BlockStatement";
551+
552+
let replacement = inBlock ? "{" : "";
553+
replacement +=
554+
declarations.length > 0 ? ` var ${declarations.join(", ")}; ` : "";
555+
replacement += inBlock ? "}" : "";
556+
550557
const dep = new ConstDependency(
551558
`// removed by dead control flow\n${replacement}`,
552559
/** @type {Range} */ (statement.range)

0 commit comments

Comments
 (0)