fix(es/modules): Preserve extensions (#4524)

This commit is contained in:
Donny/강동윤 2022-05-05 00:07:28 +09:00 committed by GitHub
parent cb6eca2fe0
commit f3b262e340
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 49 additions and 9 deletions

View File

@ -0,0 +1,17 @@
{
"jsc": {
"baseUrl": "./src",
"paths": {
"@modules/*": [
"./modules/*"
]
},
"target": "es2020",
"parser": {
"syntax": "typescript"
}
},
"module": {
"type": "es6"
}
}

View File

@ -0,0 +1,5 @@
// We keep the .js extension for ESModules, but SWC will strip it:
import { modulo } from "@modules/modulo.js";
import { sum } from "./sum.js";
console.log(modulo(sum(1, 2), 2));

View File

@ -0,0 +1,4 @@
// We keep the .js extension for ESModules, but SWC will strip it:
import { modulo } from "./modules/modulo.js";
import { sum } from "./sum.js";
console.log(modulo(sum(1, 2), 2));

View File

@ -55,9 +55,7 @@ fn find_package_root(path: &Path) -> Option<PathBuf> {
None
}
pub fn to_absolute_path(path: impl AsRef<Path>) -> Result<PathBuf, Error> {
let path = path.as_ref();
pub fn to_absolute_path(path: &Path) -> Result<PathBuf, Error> {
let absolute_path = if path.is_absolute() {
path.to_path_buf()
} else {

View File

@ -100,9 +100,9 @@ where
R: Resolve,
{
fn resolve_import(&self, base: &FileName, module_specifier: &str) -> Result<JsWord, Error> {
fn to_specifier(target_path: &str, is_file: Option<bool>) -> JsWord {
fn to_specifier(target_path: &str, is_file: Option<bool>, had_speicifer: bool) -> JsWord {
let mut p = PathBuf::from(target_path);
if is_file.unwrap_or_else(|| p.is_file()) {
if !had_speicifer && is_file.unwrap_or_else(|| p.is_file()) {
if let Some(v) = p.extension() {
if v == "ts" || v == "tsx" || v == "js" || v == "jsx" {
p.set_extension("");
@ -130,6 +130,12 @@ where
debug!("invoking resolver");
}
let had_speicifer = module_specifier
.split('/')
.last()
.map(|s| s.contains('.'))
.unwrap_or(false);
let target = self.resolver.resolve(base, module_specifier);
let target = match target {
Ok(v) => v,
@ -141,7 +147,7 @@ where
let target = match target {
FileName::Real(v) => v,
FileName::Custom(s) => return Ok(to_specifier(&s, None)),
FileName::Custom(s) => return Ok(to_specifier(&s, None, had_speicifer)),
_ => {
unreachable!(
"Node path provider does not support using `{:?}` as a target file name",
@ -178,7 +184,13 @@ where
let rel_path = match rel_path {
Some(v) => v,
None => return Ok(to_specifier(&target.display().to_string(), Some(is_file))),
None => {
return Ok(to_specifier(
&target.display().to_string(),
Some(is_file),
had_speicifer,
))
}
};
{
@ -215,9 +227,13 @@ where
Cow::Owned(format!("./{}", s))
};
if cfg!(target_os = "windows") {
Ok(to_specifier(&s.replace('\\', "/"), Some(is_file)))
Ok(to_specifier(
&s.replace('\\', "/"),
Some(is_file),
had_speicifer,
))
} else {
Ok(to_specifier(&s, Some(is_file)))
Ok(to_specifier(&s, Some(is_file), had_speicifer))
}
}
}