Skip to content

Commit

Permalink
fix(es/minifier): Fix detection of this (#9339)
Browse files Browse the repository at this point in the history
**Related issue:**

 - Closes #9148
  • Loading branch information
kdy1 committed Jul 29, 2024
1 parent 67aadfa commit 77da7cf
Show file tree
Hide file tree
Showing 6 changed files with 80 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/wicked-pandas-lick.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
swc_ecma_minifier: patch
---

fix(es/minifier): Fix detection of `this`
32 changes: 32 additions & 0 deletions crates/swc_ecma_minifier/src/compress/optimize/unused.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,6 +846,38 @@ impl Optimizer<'_> {
PropOrSpread::Prop(prop) => prop,
};

match &**prop {
Prop::Method(prop) => {
if contains_this_expr(&prop.function.body) {
return None;
}
}
Prop::Getter(prop) => {
if contains_this_expr(&prop.body) {
return None;
}
}
Prop::Setter(prop) => {
if contains_this_expr(&prop.body) {
return None;
}
}
Prop::KeyValue(prop) => match &*prop.value {
Expr::Fn(f) => {
if contains_this_expr(&f.function.body) {
return None;
}
}
Expr::Arrow(f) => {
if contains_this_expr(&f.body) {
return None;
}
}
_ => {}
},
_ => {}
}

if contains_this_expr(prop) {
return None;
}
Expand Down
6 changes: 6 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/8643/output.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ const Cache = {
get: function(key) {
if (!1 !== this.enabled) // console.log( 'THREE.Cache', 'Checking key:', key );
return this.files[key];
},
remove: function(key) {
delete this.files[key];
},
clear: function() {
this.files = {};
}
};
class Loader {
Expand Down
16 changes: 16 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/9148/input.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function foo() {
const obj = {
clear: function () {
console.log('clear')
},
start: function () {
const _this = this;
setTimeout(function () {
_this.clear();
});
}
};
return () => obj.start()
};

export default foo()
14 changes: 14 additions & 0 deletions crates/swc_ecma_minifier/tests/fixture/issues/9148/output.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
export default (function() {
const obj = {
clear: function() {
console.log('clear');
},
start: function() {
const _this = this;
setTimeout(function() {
_this.clear();
});
}
};
return ()=>obj.start();
})();
Original file line number Diff line number Diff line change
@@ -1 +1,7 @@
console.log(1, 1);
var o = {
u: function() {
return this === this;
},
p: 1
};
console.log(o.p, o.p);

0 comments on commit 77da7cf

Please sign in to comment.