fix: Mark file as ESM if it has an export from auto-cjs pass (#60216)

### What?

Improve `auto-cjs` pass to consider `export` statements.

### Why?

The previous code caused some problems.

### How?

Fixes #60197


Closes PACK-2195

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
This commit is contained in:
Donny/강동윤 2024-01-05 00:24:27 +09:00 committed by GitHub
parent b03381c432
commit 1216422454
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 37 additions and 12 deletions

View file

@ -6,12 +6,13 @@ use turbopack_binding::swc::core::ecma::{
pub(crate) fn contains_cjs(m: &Module) -> bool {
let mut v = CjsFinder::default();
m.visit_with(&mut v);
v.found
v.found && !v.is_esm
}
#[derive(Copy, Clone, Default)]
struct CjsFinder {
found: bool,
is_esm: bool,
}
impl CjsFinder {
@ -114,4 +115,13 @@ impl Visit for CjsFinder {
n.visit_children_with(self);
}
fn visit_module_decl(&mut self, n: &ModuleDecl) {
match n {
ModuleDecl::Import(_) => {}
_ => {
self.is_esm = true;
}
}
}
}

View file

@ -1,14 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "default", {
enumerable: true,
get: function() {
return _default;
}
});
var _default = 1;
export default 1;
Object.defineProperty(exports, "__esModule", {
value: true
});

View file

@ -0,0 +1,16 @@
var module = {}
;(function main(global, module) {
module.exports = function () {}
module.exports.create = () => {}
})(
(function () {
return this || {}
})(),
module,
false
)
export default module.exports
export var create = module.exports.create

View file

@ -0,0 +1,9 @@
var module = {};
(function main(global, module) {
module.exports = function() {};
module.exports.create = function() {};
})(function() {
return this || {};
}(), module, false);
export default module.exports;
export var create = module.exports.create;