Skip to content

Commit

Permalink
feat(minifier): remove empty if statment if (test) {} -> test (#8336
Browse files Browse the repository at this point in the history
)
  • Loading branch information
Boshen committed Jan 8, 2025
1 parent a76dfae commit 6220e05
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
22 changes: 22 additions & 0 deletions crates/oxc_minifier/src/ast_passes/peephole_remove_dead_code.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,13 +174,29 @@ impl<'a, 'b> PeepholeRemoveDeadCode {
self.changed = true;
}
}
Some(Statement::BlockStatement(s)) if s.body.is_empty() => {
if_stmt.alternate = None;
self.changed = true;
}
Some(Statement::EmptyStatement(_)) => {
if_stmt.alternate = None;
self.changed = true;
}
_ => {}
}

// `if (test) {}` -> `test`
if if_stmt.alternate.is_none()
&& match &if_stmt.consequent {
Statement::EmptyStatement(_) => true,
Statement::BlockStatement(s) => s.body.is_empty(),
_ => false,
}
{
let expr = ctx.ast.move_expression(&mut if_stmt.test);
return Some(ctx.ast.statement_expression(if_stmt.span, expr));
}

match ctx.get_boolean_value(&if_stmt.test) {
Some(true) => Some(ctx.ast.move_statement(&mut if_stmt.consequent)),
Some(false) => {
Expand Down Expand Up @@ -712,4 +728,10 @@ mod test {
fold("try {} catch (e) { foo() } finally { let x = bar() }", "{ let x = bar();}");
fold("try {} catch () { } finally {}", "");
}

#[test]
fn test_fold_if_statement() {
test("if (foo) {}", "foo");
test("if (foo) {} else {}", "foo");
}
}
10 changes: 5 additions & 5 deletions tasks/minsize/minsize.snap
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ Original | minified | minified | gzip | gzip | Fixture

287.63 kB | 90.04 kB | 90.07 kB | 32.06 kB | 31.95 kB | jquery.js

342.15 kB | 118.15 kB | 118.14 kB | 44.51 kB | 44.37 kB | vue.js
342.15 kB | 118.14 kB | 118.14 kB | 44.51 kB | 44.37 kB | vue.js

544.10 kB | 71.75 kB | 72.48 kB | 26.16 kB | 26.20 kB | lodash.js

Expand All @@ -17,11 +17,11 @@ Original | minified | minified | gzip | gzip | Fixture

1.25 MB | 652.56 kB | 646.76 kB | 163.52 kB | 163.73 kB | three.js

2.14 MB | 725.98 kB | 724.14 kB | 180.13 kB | 181.07 kB | victory.js
2.14 MB | 726.04 kB | 724.14 kB | 180.15 kB | 181.07 kB | victory.js

3.20 MB | 1.01 MB | 1.01 MB | 331.80 kB | 331.56 kB | echarts.js
3.20 MB | 1.01 MB | 1.01 MB | 331.83 kB | 331.56 kB | echarts.js

6.69 MB | 2.32 MB | 2.31 MB | 492.75 kB | 488.28 kB | antd.js
6.69 MB | 2.32 MB | 2.31 MB | 492.72 kB | 488.28 kB | antd.js

10.95 MB | 3.50 MB | 3.49 MB | 908.36 kB | 915.50 kB | typescript.js
10.95 MB | 3.50 MB | 3.49 MB | 908.29 kB | 915.50 kB | typescript.js

0 comments on commit 6220e05

Please sign in to comment.