diff --git a/packages/transformers/js/core/src/collect.rs b/packages/transformers/js/core/src/collect.rs index ee2ab4d64ed..5abd717b0a0 100644 --- a/packages/transformers/js/core/src/collect.rs +++ b/packages/transformers/js/core/src/collect.rs @@ -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); } diff --git a/packages/transformers/js/core/src/hoist.rs b/packages/transformers/js/core/src/hoist.rs index da0108eda26..40ce3cc1719 100644 --- a/packages/transformers/js/core/src/hoist.rs +++ b/packages/transformers/js/core/src/hoist.rs @@ -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(