feat(es/module/cjs): Support import.meta.url (#4087)

This commit is contained in:
Donny/강동윤 2022-03-19 16:05:11 +09:00 committed by GitHub
parent 9fa04fb2e7
commit d0f687bf44
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 59 additions and 3 deletions

View File

@ -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)
}

View File

@ -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,
}
}
}

View File

@ -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,
"

View File

@ -0,0 +1 @@
console.log(import.meta.url);

View File

@ -0,0 +1,2 @@
"use strict";
console.log(require("url").pathToFileURL(__filename).toString().url);