Skip to content

Commit 77da7cf

Browse files
authoredJul 29, 2024··
fix(es/minifier): Fix detection of this (#9339)
**Related issue:** - Closes #9148
1 parent 67aadfa commit 77da7cf

File tree

6 files changed

+80
-1
lines changed

6 files changed

+80
-1
lines changed
 

‎.changeset/wicked-pandas-lick.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
swc_ecma_minifier: patch
3+
---
4+
5+
fix(es/minifier): Fix detection of `this`

‎crates/swc_ecma_minifier/src/compress/optimize/unused.rs

+32
Original file line numberDiff line numberDiff line change
@@ -846,6 +846,38 @@ impl Optimizer<'_> {
846846
PropOrSpread::Prop(prop) => prop,
847847
};
848848

849+
match &**prop {
850+
Prop::Method(prop) => {
851+
if contains_this_expr(&prop.function.body) {
852+
return None;
853+
}
854+
}
855+
Prop::Getter(prop) => {
856+
if contains_this_expr(&prop.body) {
857+
return None;
858+
}
859+
}
860+
Prop::Setter(prop) => {
861+
if contains_this_expr(&prop.body) {
862+
return None;
863+
}
864+
}
865+
Prop::KeyValue(prop) => match &*prop.value {
866+
Expr::Fn(f) => {
867+
if contains_this_expr(&f.function.body) {
868+
return None;
869+
}
870+
}
871+
Expr::Arrow(f) => {
872+
if contains_this_expr(&f.body) {
873+
return None;
874+
}
875+
}
876+
_ => {}
877+
},
878+
_ => {}
879+
}
880+
849881
if contains_this_expr(prop) {
850882
return None;
851883
}

‎crates/swc_ecma_minifier/tests/fixture/issues/8643/output.js

+6
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,12 @@ const Cache = {
88
get: function(key) {
99
if (!1 !== this.enabled) // console.log( 'THREE.Cache', 'Checking key:', key );
1010
return this.files[key];
11+
},
12+
remove: function(key) {
13+
delete this.files[key];
14+
},
15+
clear: function() {
16+
this.files = {};
1117
}
1218
};
1319
class Loader {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
function foo() {
2+
const obj = {
3+
clear: function () {
4+
console.log('clear')
5+
},
6+
start: function () {
7+
const _this = this;
8+
setTimeout(function () {
9+
_this.clear();
10+
});
11+
}
12+
};
13+
return () => obj.start()
14+
};
15+
16+
export default foo()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export default (function() {
2+
const obj = {
3+
clear: function() {
4+
console.log('clear');
5+
},
6+
start: function() {
7+
const _this = this;
8+
setTimeout(function() {
9+
_this.clear();
10+
});
11+
}
12+
};
13+
return ()=>obj.start();
14+
})();
Original file line numberDiff line numberDiff line change
@@ -1 +1,7 @@
1-
console.log(1, 1);
1+
var o = {
2+
u: function() {
3+
return this === this;
4+
},
5+
p: 1
6+
};
7+
console.log(o.p, o.p);

0 commit comments

Comments
 (0)
Please sign in to comment.