mirror of
https://github.com/swc-project/swc.git
synced 2024-12-24 14:16:12 +03:00
feat(es/module/cjs): Support import.meta.url
(#4087)
This commit is contained in:
parent
9fa04fb2e7
commit
d0f687bf44
@ -915,7 +915,57 @@ impl Fold for CommonJs {
|
||||
stmts
|
||||
}
|
||||
|
||||
fn fold_expr(&mut self, expr: Expr) -> Expr {
|
||||
fn fold_expr(&mut self, mut expr: Expr) -> Expr {
|
||||
if !self.config.preserve_import_meta {
|
||||
// https://github.com/swc-project/swc/issues/1202
|
||||
if let Expr::Member(MemberExpr {
|
||||
obj,
|
||||
prop: MemberProp::Ident(prop),
|
||||
..
|
||||
}) = &mut expr
|
||||
{
|
||||
if &*prop.sym == "url" {
|
||||
if let Expr::MetaProp(MetaPropExpr {
|
||||
span,
|
||||
kind: MetaPropKind::ImportMeta,
|
||||
..
|
||||
}) = &**obj
|
||||
{
|
||||
// require('url').pathToFileURL(__filename).toString()
|
||||
|
||||
let url_module = CallExpr {
|
||||
span: DUMMY_SP,
|
||||
callee: quote_ident!("require").as_callee(),
|
||||
args: vec!["url".as_arg()],
|
||||
type_args: Default::default(),
|
||||
};
|
||||
|
||||
let url_obj = CallExpr {
|
||||
span: DUMMY_SP,
|
||||
callee: url_module
|
||||
.make_member(quote_ident!("pathToFileURL"))
|
||||
.as_callee(),
|
||||
args: vec![Ident::new(
|
||||
"__filename".into(),
|
||||
DUMMY_SP.with_ctxt(
|
||||
SyntaxContext::empty().apply_mark(self.top_level_mark),
|
||||
),
|
||||
)
|
||||
.as_arg()],
|
||||
type_args: Default::default(),
|
||||
};
|
||||
|
||||
*obj = Box::new(Expr::Call(CallExpr {
|
||||
span: *span,
|
||||
callee: url_obj.make_member(quote_ident!("toString")).as_callee(),
|
||||
args: Default::default(),
|
||||
type_args: Default::default(),
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let top_level = self.in_top_level;
|
||||
Scope::fold_expr(self, quote_ident!("exports"), top_level, expr)
|
||||
}
|
||||
|
@ -49,6 +49,8 @@ pub struct Config {
|
||||
pub no_interop: bool,
|
||||
#[serde(default)]
|
||||
pub ignore_dynamic: bool,
|
||||
#[serde(default)]
|
||||
pub preserve_import_meta: bool,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
@ -59,6 +61,7 @@ impl Default for Config {
|
||||
lazy: Lazy::default(),
|
||||
no_interop: false,
|
||||
ignore_dynamic: false,
|
||||
preserve_import_meta: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -4923,7 +4923,7 @@ test!(
|
||||
strict: true,
|
||||
strict_mode: true,
|
||||
lazy: Lazy::Bool(false),
|
||||
ignore_dynamic: false
|
||||
..Default::default()
|
||||
}),
|
||||
issue_1480_1,
|
||||
"
|
||||
@ -4944,7 +4944,7 @@ test!(
|
||||
strict: true,
|
||||
strict_mode: true,
|
||||
lazy: Lazy::Bool(false),
|
||||
ignore_dynamic: false
|
||||
..Default::default()
|
||||
}),
|
||||
issue_1480_2,
|
||||
"
|
||||
|
@ -0,0 +1 @@
|
||||
console.log(import.meta.url);
|
@ -0,0 +1,2 @@
|
||||
"use strict";
|
||||
console.log(require("url").pathToFileURL(__filename).toString().url);
|
Loading…
Reference in New Issue
Block a user