Skip to content

Commit 452fc98

Browse files
authored
fix(es/minifier): Hoist props when only props are used (#10891)
**Description:** We should not break the obj declaration into var declarations of its props if the obj var is directly used somewhere. Not sure if the condition `accessed_props_count < usage.ref_count` is too strong or too weak. **Related issue:** - Closes #10849
1 parent 0047c39 commit 452fc98

File tree

5 files changed

+27
-1
lines changed

5 files changed

+27
-1
lines changed

.changeset/selfish-colts-smell.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
swc_core: patch
3+
swc_ecma_minifier: patch
4+
---
5+
6+
fix(es/minifier): hoist props when only props are usd
Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
11
//// [nullishCoalescingOperator12.ts]
22
var _obj_arr;
3-
for (const i of null != (_obj_arr = null == obj ? void 0 : []) ? _obj_arr : []);
3+
const obj = {
4+
arr: []
5+
};
6+
for (const i of null != (_obj_arr = null == obj ? void 0 : obj.arr) ? _obj_arr : []);

crates/swc_ecma_minifier/src/compress/optimize/props.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,15 @@ impl Optimizer<'_> {
6060
return None;
6161
}
6262

63+
let accessed_props_count: u32 = usage.accessed_props.values().sum();
64+
if accessed_props_count < usage.ref_count {
65+
log_abort!(
66+
"hoist_props: Variable `{}` is directly used without accessing its properties",
67+
name.id
68+
);
69+
return None;
70+
}
71+
6372
// We should abort if unknown property is used.
6473
let mut unknown_used_props = self
6574
.data
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
(function () {
2+
const obj = { value: 42 };
3+
console.log(obj === null || obj === void 0 ? void 0 : obj.value);
4+
})();
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
const obj = {
2+
value: 42
3+
};
4+
console.log(null == obj ? void 0 : obj.value);

0 commit comments

Comments
 (0)