Skip to content

Commit

Permalink
fix(es/minifier): Drop console in optional chainings (#9759)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #9757
  • Loading branch information
CPunisher authored Nov 25, 2024
1 parent 04e01ef commit 39271ad
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 33 deletions.
6 changes: 6 additions & 0 deletions .changeset/dirty-ways-remain.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
swc_core: patch
swc_ecma_minifier: patch
---

fix(es/minifier): drop console in opt chains
69 changes: 36 additions & 33 deletions crates/swc_ecma_minifier/src/compress/pure/drop_console.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,47 @@ impl Pure<'_> {
return;
}

if let Expr::Call(CallExpr { callee, .. }) = e {
// Find console.log
let callee = match callee {
Callee::Expr(callee) => callee,
_ => return,
};
let Some(callee) = (match e {
Expr::Call(call) => call.callee.as_expr(),
Expr::OptChain(opt_chain) => opt_chain.base.as_call().map(|call| &call.callee),
_ => None,
}) else {
return;
};

if let Expr::Member(MemberExpr {
obj: callee_obj,
prop: MemberProp::Ident(_),
..
}) = &**callee
{
let mut loop_co = &**callee_obj;
loop {
match loop_co {
Expr::Ident(obj) => {
if obj.sym != *"console" {
return;
}
break;
}
let Some(mut loop_co) = (match callee.as_ref() {
Expr::Member(member) => Some(&member.obj),
Expr::OptChain(opt_chain) => opt_chain.base.as_member().map(|member| &member.obj),
_ => None,
}) else {
return;
};

Expr::Member(MemberExpr {
obj: loop_co_obj,
prop: MemberProp::Ident(_),
..
}) => {
loop_co = loop_co_obj;
}
_ => return,
loop {
match loop_co.as_ref() {
Expr::Ident(obj) => {
if obj.sym != *"console" {
return;
}
break;
}

report_change!("drop_console: Removing console call");
self.changed = true;
*e = *Expr::undefined(DUMMY_SP);
Expr::Member(MemberExpr {
obj: loop_co_obj,
prop: MemberProp::Ident(_),
..
}) => {
loop_co = loop_co_obj;
}
Expr::OptChain(opt_chain) => match opt_chain.base.as_member() {
Some(member) => loop_co = &member.obj,
None => return,
},
_ => return,
}
}

report_change!("drop_console: Removing console call");
self.changed = true;
*e = *Expr::undefined(DUMMY_SP);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"unused": true,
"drop_console": true
}
7 changes: 7 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/9757/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function A() {
console?.log?.(123);
console?.log?.apply(console, arguments);
console?.a.b?.c(console, arguments);
console?.any();
console?.warn();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default function A() {}

0 comments on commit 39271ad

Please sign in to comment.