Skip to content

Commit 943fb40

Browse files
authored
Detect TSC polyfills to avoid marking them as CJS (#9318)
1 parent bc5c715 commit 943fb40

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

packages/transformers/js/core/src/collect.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -767,6 +767,27 @@ impl Visit for Collect {
767767
self.used_imports.insert(id!(ident));
768768
}
769769
}
770+
Expr::Bin(bin_expr) => {
771+
if self.in_module_this {
772+
// Some TSC polyfills use a pattern like below.
773+
// We want to avoid marking these modules as CJS
774+
// e.g. var _polyfill = (this && this.polyfill) || function () {}
775+
if matches!(bin_expr.op, BinaryOp::LogicalAnd) && matches!(*bin_expr.left, Expr::This(..))
776+
{
777+
match &*bin_expr.right {
778+
Expr::Member(member_expr) => {
779+
if matches!(*member_expr.obj, Expr::This(..))
780+
&& matches!(member_expr.prop, MemberProp::Ident(..))
781+
{
782+
return;
783+
}
784+
}
785+
_ => {}
786+
}
787+
}
788+
}
789+
node.visit_children_with(self);
790+
}
770791
_ => {
771792
node.visit_children_with(self);
772793
}

packages/transformers/js/core/src/hoist.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1424,6 +1424,32 @@ mod tests {
14241424
assert!(collect.should_wrap);
14251425
}
14261426

1427+
#[test]
1428+
fn collect_has_cjs_exports() {
1429+
let (collect, _code, _hoist) = parse(
1430+
r#"
1431+
module.exports = {};
1432+
"#,
1433+
);
1434+
assert!(collect.has_cjs_exports);
1435+
1436+
let (collect, _code, _hoist) = parse(
1437+
r#"
1438+
this.someExport = 'true';
1439+
"#,
1440+
);
1441+
assert!(collect.has_cjs_exports);
1442+
1443+
// Some TSC polyfills use a pattern like below.
1444+
// We want to avoid marking these modules as CJS
1445+
let (collect, _code, _hoist) = parse(
1446+
r#"
1447+
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function () {}
1448+
"#,
1449+
);
1450+
assert!(!collect.has_cjs_exports);
1451+
}
1452+
14271453
#[test]
14281454
fn collect_should_wrap() {
14291455
let (collect, _code, _hoist) = parse(

0 commit comments

Comments
 (0)