Skip to content

Commit

Permalink
fix: #1007 (#1738)
Browse files Browse the repository at this point in the history
support BinaryExpression

Co-authored-by: shikuan.sk <[email protected]>
  • Loading branch information
notcold and shikuan.sk authored Jan 8, 2025
1 parent c95962a commit 5714d19
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 4 deletions.
36 changes: 32 additions & 4 deletions crates/mako/src/visitors/try_resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ use std::sync::Arc;

use swc_core::common::Mark;
use swc_core::ecma::ast::{
AssignExpr, BlockStmt, CallExpr, Decl, Expr, ExprOrSpread, ExprStmt, ReturnStmt, Stmt, TryStmt,
AssignExpr, BinExpr, BlockStmt, CallExpr, Decl, Expr, ExprOrSpread, ExprStmt, ReturnStmt, Stmt,
TryStmt,
};
use swc_core::ecma::visit::{VisitMut, VisitMutWith};

Expand Down Expand Up @@ -95,9 +96,19 @@ impl VisitMut for TryResolve {
if let Some(Expr::Call(call_expr)) = decl.init.as_deref_mut() {
self.handle_call_expr(call_expr);
}
// support `const a = 1 && require('not-found-module');`
// when decl.init is BinaryExpression, handle left and right recursively
// ref: https://github.com/umijs/mako/issues/1007
if let Some(Expr::Bin(BinExpr {
right: right_expr,
left: left_expr,
..
})) = decl.init.as_deref_mut()
{
if let Some(call_expr) = left_expr.as_mut_call() {
self.handle_call_expr(call_expr);
}
if let Some(call_expr) = right_expr.as_mut_call() {
self.handle_call_expr(call_expr);
}
}
}
}
_ => {}
Expand Down Expand Up @@ -213,6 +224,23 @@ try {
);
}

#[test]
fn test_try_require_handle_require_binary_defined() {
assert_eq!(
run(r#"try{const a=0||require('foo');}catch(e){}"#),
r#"
try {
const a = 0 || require(Object(function makoMissingModule() {
var e = new Error("Cannot find module 'foo'");
e.code = "MODULE_NOT_FOUND";
throw e;
}()));
} catch (e) {}
"#
.trim()
);
}

fn run(js_code: &str) -> String {
let mut test_utils = TestUtils::gen_js_ast(js_code);
let ast = test_utils.ast.js_mut();
Expand Down
6 changes: 6 additions & 0 deletions e2e/fixtures/resolve.failed-in-try-statement/expect.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,9 @@ assert.match(
/Cannot find module '\.\/hoo'/,
"should support failed var x = require('...') in try statement"
);

assert.match(
content,
/Cannot find module '\.\/hoo'/,
"should support failed var x = 0 || require('...') in try statement"
);
5 changes: 5 additions & 0 deletions e2e/fixtures/resolve.failed-in-try-statement/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@ try {
exports.xx = require('./bar');
} catch(e) {}

try {
const b = 0 || require('./faa');
} catch(e) {}


try {
const a = require('./hoo'), b = 1;
} catch(e) {}

0 comments on commit 5714d19

Please sign in to comment.