Skip to content

Commit

Permalink
fix: Mark file as ESM if it has an export from auto-cjs pass (verce…
Browse files Browse the repository at this point in the history
…l#60216)

### What?

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

### Why?

The previous code caused some problems.

### How?

Fixes vercel#60197


Closes PACK-2195

---------

Co-authored-by: Jiachi Liu <inbox@huozhi.im>
  • Loading branch information
2 people authored and agustints committed Jan 6, 2024
1 parent d1171f5 commit 2497907
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 12 deletions.
12 changes: 11 additions & 1 deletion packages/next-swc/crates/core/src/auto_cjs/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
}
}
}
}
12 changes: 1 addition & 11 deletions packages/next-swc/crates/core/tests/loader/auto-cjs/2/output.js
Original file line number Diff line number Diff line change
@@ -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
});
Original file line number Diff line number Diff line change
@@ -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
Original file line number Diff line number Diff line change
@@ -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;

0 comments on commit 2497907

Please sign in to comment.