diff --git a/crates/mako/src/visitors/try_resolve.rs b/crates/mako/src/visitors/try_resolve.rs index 85fbf0502..2d0735ee8 100644 --- a/crates/mako/src/visitors/try_resolve.rs +++ b/crates/mako/src/visitors/try_resolve.rs @@ -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}; @@ -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); + } + } } } _ => {} @@ -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(); diff --git a/e2e/fixtures/resolve.failed-in-try-statement/expect.js b/e2e/fixtures/resolve.failed-in-try-statement/expect.js index 17043e21e..5978556ed 100644 --- a/e2e/fixtures/resolve.failed-in-try-statement/expect.js +++ b/e2e/fixtures/resolve.failed-in-try-statement/expect.js @@ -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" +); diff --git a/e2e/fixtures/resolve.failed-in-try-statement/src/index.tsx b/e2e/fixtures/resolve.failed-in-try-statement/src/index.tsx index 98f49b8af..d11335c1f 100644 --- a/e2e/fixtures/resolve.failed-in-try-statement/src/index.tsx +++ b/e2e/fixtures/resolve.failed-in-try-statement/src/index.tsx @@ -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) {}