Skip to content

Commit dd8ff69

Browse files
authored
tsparser: perfer type declarations over javascript (#2192)
e.g drizzle use imports like these: ```ts import type { Simplify, Update } from "./utils.js"; ``` but the types are not available in the .js file, however there is a utils.d.ts See https://www.typescriptlang.org/docs/handbook/modules/theory.html#the-role-of-declaration-files If I understand this correctly we should look for declarations if they exist when we encounter an import like this
1 parent 979215e commit dd8ff69

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

tsparser/src/runtimeresolve/node.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use std::collections::HashSet;
2+
use std::ffi::OsStr;
23
use std::{
34
fs::File,
45
io::BufReader,
@@ -147,9 +148,38 @@ where
147148
}
148149
}
149150

150-
match self.resolve_encore_module(target)? {
151-
Some(buf) => Ok(FileName::Real(buf.clean())),
152-
None => self.inner.resolve(base, target),
151+
let result = match self.resolve_encore_module(target)? {
152+
Some(buf) => FileName::Real(buf.clean()),
153+
None => self.inner.resolve(base, target)?,
154+
};
155+
156+
// Prefer TypeScript declaration files (.d.ts) over JavaScript files if they exist.
157+
if let FileName::Real(ref path) = result {
158+
if let Some(dts_path) = declaration_file(path) {
159+
return Ok(FileName::Real(dts_path));
160+
}
153161
}
162+
163+
Ok(result)
164+
}
165+
}
166+
167+
fn declaration_file(path: &Path) -> Option<PathBuf> {
168+
let ext = path.extension().and_then(OsStr::to_str)?;
169+
170+
let new_ext = match ext {
171+
"js" => "d.ts",
172+
"mjs" => "d.mts",
173+
"cjs" => "d.cts",
174+
_ => return None,
175+
};
176+
177+
let mut dts = path.to_path_buf();
178+
dts.set_extension(new_ext);
179+
180+
if dts.exists() {
181+
Some(dts)
182+
} else {
183+
None
154184
}
155185
}

0 commit comments

Comments
 (0)