mirror of
https://github.com/swc-project/swc.git
synced 2024-12-23 21:54:36 +03:00
feat(es/minifier): Improve simplification of ?.
(#6681)
**Related issue:** - Closes https://github.com/swc-project/swc/issues/6492.
This commit is contained in:
parent
6109a4c188
commit
707b1e3cd2
@ -364,6 +364,30 @@ impl Pure<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn optimize_opt_chain(&mut self, e: &mut Expr) {
|
||||
let opt = match e {
|
||||
Expr::OptChain(c) => c,
|
||||
_ => return,
|
||||
};
|
||||
|
||||
if let OptChainBase::Member(base) = &mut opt.base {
|
||||
if match &*base.obj {
|
||||
Expr::Lit(Lit::Null(..)) => false,
|
||||
Expr::Lit(..) | Expr::Object(..) | Expr::Array(..) => true,
|
||||
_ => false,
|
||||
} {
|
||||
self.changed = true;
|
||||
report_change!("Optimized optional chaining expression where object is not null");
|
||||
|
||||
*e = Expr::Member(MemberExpr {
|
||||
span: opt.span,
|
||||
obj: base.obj.take(),
|
||||
prop: base.prop.take(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// new Array(...) -> Array(...)
|
||||
pub(super) fn optimize_builtin_object(&mut self, e: &mut Expr) {
|
||||
if !self.options.pristine_globals {
|
||||
|
@ -551,6 +551,12 @@ impl VisitMut for Pure<'_> {
|
||||
if e.is_seq() {
|
||||
debug_assert_valid(e);
|
||||
}
|
||||
|
||||
self.optimize_opt_chain(e);
|
||||
|
||||
if e.is_seq() {
|
||||
debug_assert_valid(e);
|
||||
}
|
||||
}
|
||||
|
||||
fn visit_mut_expr_stmt(&mut self, s: &mut ExprStmt) {
|
||||
|
@ -0,0 +1,3 @@
|
||||
const obj = { key: 42 };
|
||||
const val = obj?.[null || 'key']
|
||||
console.log('val', val)
|
@ -0,0 +1 @@
|
||||
console.log('val', 42);
|
@ -0,0 +1,3 @@
|
||||
const obj = { key: 42 };
|
||||
const val = obj?.key.toString()
|
||||
console.log('val', val)
|
@ -0,0 +1 @@
|
||||
console.log('val', "42");
|
@ -0,0 +1,3 @@
|
||||
const obj = { key: 42 };
|
||||
const val = obj?.key?.toString()
|
||||
console.log('val', val)
|
@ -0,0 +1 @@
|
||||
console.log('val', "42");
|
@ -0,0 +1,3 @@
|
||||
const obj = { key: 42 };
|
||||
const val = obj.key?.toString()
|
||||
console.log('val', val)
|
@ -0,0 +1 @@
|
||||
console.log('val', "42");
|
Loading…
Reference in New Issue
Block a user