Skip to content

Commit

Permalink
fix(es/minifier): Keep class with a static block (#8283)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #8271.
  • Loading branch information
Austaras authored Nov 14, 2023
1 parent 0c05f6e commit 20fb5ba
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -373,8 +373,26 @@ class C extends B {
}
export { };
//// [inContainingClassExprStaticField.ts]
(class {
static{
class C extends B {
static{
this._ = super.w();
}
}
}
});
export { };
//// [inContainingClassExprStaticBlock.ts]
(class {
static{
class C extends B {
static{
super.w();
}
}
}
});
export { };
//// [funcExprInContainingScopeStaticField.ts]
class C extends B {
Expand Down
10 changes: 10 additions & 0 deletions crates/swc_ecma_minifier/src/compress/optimize/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,16 @@ impl Optimizer<'_> {
}

Expr::Class(cls) => {
if cls
.class
.body
.iter()
.any(|m| m.as_static_block().iter().any(|s| !s.body.is_empty()))
{
// there's nothing we can do about it
return Some(Expr::Class(cls.take()));
}

let exprs: Vec<Box<Expr>> =
extract_class_side_effect(&self.expr_ctx, *cls.class.take())
.into_iter()
Expand Down
21 changes: 21 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/8271/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
let $eb2fd35624c84372$var$A = (() => {
let _classDecorators = [$eb2fd35624c84372$var$CustomElement("component-a")];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
let _classSuper = HTMLElement;
var A = class extends _classSuper {
static {
_classThis = this;
}
static {
console.log(123);
}
constructor() {
super();
this.innerHTML = "Component A is working";
}
};
return (A = _classThis);
})();
console.log(new $eb2fd35624c84372$var$A().tagName);
16 changes: 16 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/8271/output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
console.log(new ((()=>{
let _classThis;
$eb2fd35624c84372$var$CustomElement("component-a");
let _classSuper = HTMLElement;
return class extends _classSuper {
static{
_classThis = this;
}
static{
console.log(123);
}
constructor(){
super(), this.innerHTML = "Component A is working";
}
}, _classThis;
})())().tagName);
6 changes: 5 additions & 1 deletion crates/swc_ecma_utils/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1523,7 +1523,11 @@ pub fn class_has_side_effect(expr_ctx: &ExprCtx, c: &Class) -> bool {
}
}
}

ClassMember::StaticBlock(s) => {
if !s.body.stmts.is_empty() {
return true;
}
}
_ => {}
}
}
Expand Down

0 comments on commit 20fb5ba

Please sign in to comment.