Skip to content

Commit

Permalink
Fix edge case in the CJS optimizer (#50258)
Browse files Browse the repository at this point in the history
Previously we are ignoring idents in all var declarators in the check,
so it's still possible to fail in some edge cases. CC @kdy1
  • Loading branch information
shuding authored May 24, 2023
1 parent fcfd630 commit 18ba208
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/next-swc/crates/core/src/cjs_optimizer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,9 +255,28 @@ impl Visit for Analyzer<'_> {
noop_visit_type!();

fn visit_var_declarator(&mut self, n: &VarDeclarator) {
self.in_member_or_var = true;
n.visit_children_with(self);
self.in_member_or_var = false;
let mut safe_to_ignore = false;

// Ignore the require itself (foo = require('foo'))
if let Some(Expr::Call(CallExpr {
callee: Callee::Expr(callee),
..
})) = n.init.as_deref()
{
if let Expr::Ident(ident) = &**callee {
if ident.sym == *"require" {
safe_to_ignore = true;
}
}
}

if safe_to_ignore {
self.in_member_or_var = true;
n.visit_children_with(self);
self.in_member_or_var = false;
} else {
n.visit_children_with(self);
}
}

fn visit_member_expr(&mut self, e: &MemberExpr) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const foo = require('next/server')
const bar = foo

console.log(bar)
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
const foo = require('next/server');
const bar = foo;

console.log(bar);

0 comments on commit 18ba208

Please sign in to comment.