Skip to content

Commit

Permalink
fix: __webpack_public_path__ and __mako_public_path__ should not be r…
Browse files Browse the repository at this point in the history
…eplaced when it's defined by user (#1442)
  • Loading branch information
sorrycc authored Jul 23, 2024
1 parent f28922b commit 37450e3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
2 changes: 1 addition & 1 deletion crates/mako/src/build/transform.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ impl Transform {
context: context.clone(),
unresolved_mark,
}));
visitors.push(Box::new(PublicPathAssignment {}));
visitors.push(Box::new(PublicPathAssignment { unresolved_mark }));
// TODO: refact provide
visitors.push(Box::new(Provide::new(
context.config.providers.clone(),
Expand Down
34 changes: 30 additions & 4 deletions crates/mako/src/visitors/public_path_assignment.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
use swc_core::common::DUMMY_SP;
use swc_core::common::{Mark, DUMMY_SP};
use swc_core::ecma::ast::{AssignExpr, AssignOp, Pat, PatOrExpr};
use swc_core::ecma::utils::member_expr;
use swc_core::ecma::visit::{VisitMut, VisitMutWith};

pub struct PublicPathAssignment {}
pub struct PublicPathAssignment {
pub unresolved_mark: Mark,
}

impl VisitMut for PublicPathAssignment {
fn visit_mut_assign_expr(&mut self, n: &mut AssignExpr) {
if n.op == AssignOp::Assign {
if let PatOrExpr::Pat(box Pat::Ident(ident)) = &n.left {
let sym = ident.sym.as_ref();
if sym == "__webpack_public_path__" || sym == "__mako_public_path__" {
if ident.span.ctxt.outer() == self.unresolved_mark
&& (sym == "__webpack_public_path__" || sym == "__mako_public_path__")
{
*n = AssignExpr {
left: PatOrExpr::Expr(member_expr!(DUMMY_SP, __mako_require__.publicPath)),
..n.clone()
Expand Down Expand Up @@ -42,11 +46,33 @@ mod tests {
);
}

#[test]
fn test_ident_defined() {
assert_eq!(
run(r#"let __webpack_public_path__ = 1; __webpack_public_path__ = '/foo/';"#),
r#"
let __webpack_public_path__ = 1;
__webpack_public_path__ = '/foo/';
"#
.trim()
);
assert_eq!(
run(r#"let __mako_public_path__ = 1; __mako_public_path__ = '/foo/';"#),
r#"
let __mako_public_path__ = 1;
__mako_public_path__ = '/foo/';
"#
.trim()
);
}

fn run(js_code: &str) -> String {
let mut test_utils = TestUtils::gen_js_ast(js_code);
let ast = test_utils.ast.js_mut();
GLOBALS.set(&test_utils.context.meta.script.globals, || {
let mut visitor = PublicPathAssignment {};
let mut visitor = PublicPathAssignment {
unresolved_mark: ast.unresolved_mark,
};
ast.ast.visit_mut_with(&mut visitor);
});
test_utils.js_ast_to_code()
Expand Down

0 comments on commit 37450e3

Please sign in to comment.