Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(es/module): Use jsc.baseUrl while resolving absolute paths #7775

Merged
merged 19 commits into from
Aug 9, 2023
2 changes: 1 addition & 1 deletion crates/swc/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1958,7 +1958,7 @@ fn build_resolver(base_url: PathBuf, paths: CompiledPaths) -> Box<SwcImportResol
);
let r = CachingResolver::new(40, r);

let r = NodeImportResolver::new(r);
let r = NodeImportResolver::with_base_dir(r, Some(base_url.clone()));
Arc::new(r)
};

Expand Down
8 changes: 6 additions & 2 deletions crates/swc/tests/fixture/deno/paths/cjs-001/input/.swcrc
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
{
"jsc": {
"baseUrl": ".",
"paths": {
"*": ["src/*", "src2/*"]
"*": [
"src/*",
"src2/*"
]
}
},
"module": {
"type": "commonjs"
}
}
}
1 change: 1 addition & 0 deletions crates/swc/tests/fixture/issues-3xxx/3272/1/input/.swcrc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"jsc": {
"baseUrl": ".",
"paths": {
"server/*": [
"./*"
Expand Down
29 changes: 24 additions & 5 deletions crates/swc_ecma_transforms_module/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,30 @@ where
R: Resolve,
{
resolver: R,
base_dir: Option<PathBuf>,
}

impl<R> NodeImportResolver<R>
where
R: Resolve,
{
#[deprecated(note = "Use `with_base_dir`")]
pub fn new(resolver: R) -> Self {
Self { resolver }
Self::with_base_dir(resolver, None)
}

pub fn with_base_dir(resolver: R, base_dir: Option<PathBuf>) -> Self {
#[cfg(not(target_arch = "wasm32"))]
if let Some(base_dir) = &base_dir {
assert!(
base_dir.is_absolute(),
"base_dir({}) must be absolute. Please ensure that `jsc.baseUrl` is specified \
correctly.",
base_dir.display()
);
}

Self { resolver, base_dir }
}
}

Expand Down Expand Up @@ -193,8 +209,8 @@ where
};

if base.is_absolute() != target.is_absolute() {
base = Cow::Owned(absolute_path(&base)?);
target = absolute_path(&target)?;
base = Cow::Owned(absolute_path(self.base_dir.as_deref(), &base)?);
target = absolute_path(self.base_dir.as_deref(), &target)?;
}

let rel_path = diff_paths(
Expand Down Expand Up @@ -259,11 +275,14 @@ impl_ref!(P, &'_ P);
impl_ref!(P, Box<P>);
impl_ref!(P, Arc<P>);

fn absolute_path(path: &Path) -> io::Result<PathBuf> {
fn absolute_path(base_dir: Option<&Path>, path: &Path) -> io::Result<PathBuf> {
let absolute_path = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()?.join(path)
match base_dir {
Some(base_dir) => base_dir.join(path),
None => current_dir()?.join(path),
}
}
.clean();

Expand Down
4 changes: 2 additions & 2 deletions crates/swc_ecma_transforms_module/tests/common_js.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,11 @@ fn tr(
let unresolved_mark = Mark::new();
let top_level_mark = Mark::new();

let avalible_set = FeatureFlag::all();
let available_set = FeatureFlag::all();

chain!(
resolver(unresolved_mark, top_level_mark, typescript),
common_js(unresolved_mark, config, avalible_set, Some(comments)),
common_js(unresolved_mark, config, available_set, Some(comments)),
)
}

Expand Down
40 changes: 19 additions & 21 deletions crates/swc_ecma_transforms_module/tests/path_node.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use std::{
env::current_dir,
path::{Path, PathBuf},
};
use std::path::{Path, PathBuf};

use indexmap::IndexMap;
use serde::Deserialize;
Expand Down Expand Up @@ -37,7 +34,9 @@ fn node_modules() {

#[test]
fn issue_4730() {
let dir = Path::new("tests/fixture-manual/issue-4730");
let dir = Path::new("tests/fixture-manual/issue-4730")
.canonicalize()
.unwrap();
let input_dir = dir.join("input");
let output_dir = dir.join("output");

Expand All @@ -47,11 +46,7 @@ fn issue_4730() {
let mut paths = IndexMap::new();
paths.insert(
"@print/a".into(),
vec![current_dir()
.unwrap()
.join("tests")
.join("fixture-manual")
.join("issue-4730")
vec![dir
.join("input")
.join("packages")
.join("a")
Expand All @@ -62,11 +57,7 @@ fn issue_4730() {
);
paths.insert(
"@print/b".into(),
vec![current_dir()
.unwrap()
.join("tests")
.join("fixture-manual")
.join("issue-4730")
vec![dir
.join("input")
.join("packages")
.join("b")
Expand Down Expand Up @@ -97,14 +88,21 @@ fn paths_resolver(
base_url: impl AsRef<Path>,
rules: Vec<(String, Vec<String>)>,
) -> JscPathsProvider {
let base_url = base_url.as_ref().to_path_buf();
let base_url = base_url
.as_ref()
.to_path_buf()
.canonicalize()
.expect("failed to canonicalize");
dbg!(&base_url);

NodeImportResolver::new(TsConfigResolver::new(
NodeModulesResolver::new(swc_ecma_loader::TargetEnv::Node, Default::default(), true),
base_url,
rules,
))
NodeImportResolver::with_base_dir(
TsConfigResolver::new(
NodeModulesResolver::new(swc_ecma_loader::TargetEnv::Node, Default::default(), true),
base_url.clone(),
rules,
),
Some(base_url),
)
}

#[derive(Deserialize)]
Expand Down
3 changes: 2 additions & 1 deletion node-swc/__tests__/transform/issue_4730_test.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import swc from "../../..";
import { dirname, join } from "path";
import { dirname, join, resolve } from "path";
import { platform } from "os";
import { fileURLToPath } from "url";

Expand All @@ -21,6 +21,7 @@ it("should work", async () => {
dynamicImport: true,
},
target: "es2020",
baseUrl: resolve('.'),
paths: {
"@print/a": [join(dir, "./packages/a/src/index.ts")],
"@print/b": [join(dir, "./packages/b/src/index.ts")],
Expand Down
17 changes: 16 additions & 1 deletion node-swc/src/binding.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
/* tslint:disable */
/* eslint-disable */
/* prettier-ignore */

/* auto-generated by NAPI-RS */

const { existsSync, readFileSync } = require('fs')
const { join } = require('path')

Expand All @@ -11,7 +17,7 @@ function isMusl() {
// For Node 10
if (!process.report || typeof process.report.getReport !== 'function') {
try {
const lddPath = require('child_process').execSync('which ldd').toString().trim();
const lddPath = require('child_process').execSync('which ldd').toString().trim()
return readFileSync(lddPath, 'utf8').includes('musl')
} catch (e) {
return true
Expand Down Expand Up @@ -102,6 +108,15 @@ switch (platform) {
}
break
case 'darwin':
localFileExisted = existsSync(join(__dirname, 'swc.darwin-universal.node'))
try {
if (localFileExisted) {
nativeBinding = require('./swc.darwin-universal.node')
} else {
nativeBinding = require('@swc/core-darwin-universal')
}
break
} catch {}
switch (arch) {
case 'x64':
localFileExisted = existsSync(join(__dirname, 'swc.darwin-x64.node'))
Expand Down