Skip to content

Commit

Permalink
Detect TSC polyfills to avoid marking them as CJS (#9318)
Browse files Browse the repository at this point in the history
  • Loading branch information
mattcompiles authored Oct 18, 2023
1 parent bc5c715 commit 943fb40
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
21 changes: 21 additions & 0 deletions packages/transformers/js/core/src/collect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,27 @@ impl Visit for Collect {
self.used_imports.insert(id!(ident));
}
}
Expr::Bin(bin_expr) => {
if self.in_module_this {
// Some TSC polyfills use a pattern like below.
// We want to avoid marking these modules as CJS
// e.g. var _polyfill = (this && this.polyfill) || function () {}
if matches!(bin_expr.op, BinaryOp::LogicalAnd) && matches!(*bin_expr.left, Expr::This(..))
{
match &*bin_expr.right {
Expr::Member(member_expr) => {
if matches!(*member_expr.obj, Expr::This(..))
&& matches!(member_expr.prop, MemberProp::Ident(..))
{
return;
}
}
_ => {}
}
}
}
node.visit_children_with(self);
}
_ => {
node.visit_children_with(self);
}
Expand Down
26 changes: 26 additions & 0 deletions packages/transformers/js/core/src/hoist.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1424,6 +1424,32 @@ mod tests {
assert!(collect.should_wrap);
}

#[test]
fn collect_has_cjs_exports() {
let (collect, _code, _hoist) = parse(
r#"
module.exports = {};
"#,
);
assert!(collect.has_cjs_exports);

let (collect, _code, _hoist) = parse(
r#"
this.someExport = 'true';
"#,
);
assert!(collect.has_cjs_exports);

// Some TSC polyfills use a pattern like below.
// We want to avoid marking these modules as CJS
let (collect, _code, _hoist) = parse(
r#"
var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function () {}
"#,
);
assert!(!collect.has_cjs_exports);
}

#[test]
fn collect_should_wrap() {
let (collect, _code, _hoist) = parse(
Expand Down

0 comments on commit 943fb40

Please sign in to comment.