diff --git a/crates/oxc_minifier/src/peephole/fold_constants.rs b/crates/oxc_minifier/src/peephole/fold_constants.rs index fedf74aa10c09..29004d038858c 100644 --- a/crates/oxc_minifier/src/peephole/fold_constants.rs +++ b/crates/oxc_minifier/src/peephole/fold_constants.rs @@ -467,9 +467,9 @@ impl<'a> PeepholeOptimizations { } // remove useless `+ ""` (e.g. `typeof foo + ""` -> `typeof foo`) - if left_expr.is_specific_string_literal("") && right_expr.value_type(&ctx).is_string() { + if Self::evaluates_to_empty_string(left_expr) && right_expr.value_type(&ctx).is_string() { return Some(ctx.ast.move_expression(right_expr)); - } else if right_expr.is_specific_string_literal("") + } else if Self::evaluates_to_empty_string(right_expr) && left_expr.value_type(&ctx).is_string() { return Some(ctx.ast.move_expression(left_expr)); @@ -478,6 +478,14 @@ impl<'a> PeepholeOptimizations { None } + fn evaluates_to_empty_string(e: &Expression<'a>) -> bool { + match e { + Expression::StringLiteral(s) => s.value.is_empty(), + Expression::ArrayExpression(a) => a.elements.is_empty(), + _ => false, + } + } + fn try_fold_left_child_op( e: &mut BinaryExpression<'a>, ctx: Ctx<'a, '_>, @@ -1839,6 +1847,10 @@ mod test { fold_same("typeof foo + '123'"); fold("typeof foo + ''", "typeof foo"); fold("'' + typeof foo", "typeof foo"); + fold("typeof foo + ``", "typeof foo"); + fold("`` + typeof foo", "typeof foo"); + fold("typeof foo + []", "typeof foo"); + fold("[] + typeof foo", "typeof foo"); fold("(foo ? 'a' : 'b') + ''", "foo ? 'a' : 'b'"); fold_same("typeof foo - ''"); } diff --git a/crates/oxc_minifier/tests/peephole/esbuild.rs b/crates/oxc_minifier/tests/peephole/esbuild.rs index fb92b0ee57554..365e4ea56e91b 100644 --- a/crates/oxc_minifier/tests/peephole/esbuild.rs +++ b/crates/oxc_minifier/tests/peephole/esbuild.rs @@ -315,8 +315,8 @@ fn js_parser_test() { test("a = typeof b + ''", "a = typeof b;"); test("a = [] + `${b}`", "a = `${b}`;"); test("a = `${b}` + []", "a = `${b}`;"); - // test("a = [] + typeof b", "a = typeof b;"); - // test("a = typeof b + []", "a = typeof b;"); + test("a = [] + typeof b", "a = typeof b;"); + test("a = typeof b + []", "a = typeof b;"); test("a = [b] + `${b}`", "a = [b] + `${b}`;"); test("a = `${b}` + [b]", "a = `${b}` + [b];"); test("a = {} + `${b}`", "a = `[object Object]${b}`;");