Skip to content

Commit 4f24b98

Browse files
committed
feat: Improve path resolution with aliases
This commit introduces a new function `getAbsPath` that improves the resolution of file paths. It now supports absolute paths, relative paths, and paths that start with an alias. The aliases are loaded from the configuration. This change makes the code more robust and flexible.
1 parent f8cb20e commit 4f24b98

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

mod.ts

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import process from "node:process";
12
import * as path from "pathe";
23
import * as fs from "node:fs/promises";
34
import MagicString, { Bundle } from "magic-string";
@@ -7,7 +8,7 @@ import type { UserConfig as ViteConfig } from "vite";
78
import { loadConfig } from "unconfig";
89

910
async function loadAliases() {
10-
const { config: { alias } } = await loadConfig({
11+
const { config } = await loadConfig({
1112
merge: true,
1213
sources: [
1314
{
@@ -26,7 +27,35 @@ async function loadAliases() {
2627
},
2728
],
2829
});
29-
return alias;
30+
return config?.alias ?? {};
31+
}
32+
33+
/**
34+
* Resolve paths
35+
*/
36+
async function getAbsPath(
37+
{ filename, file }: { filename?: string; file: string },
38+
) {
39+
const aliases = await loadAliases();
40+
const dirname = filename ? path.dirname(filename) : process.cwd();
41+
42+
if (file.startsWith("/")) {
43+
return file;
44+
}
45+
46+
if (file.startsWith("./") || file.startsWith("../")) {
47+
return path.resolve(dirname, file);
48+
}
49+
50+
for (const [alias, aliasPath] of Object.entries(aliases)) {
51+
if (file.startsWith(alias)) {
52+
const s = new MagicString(file);
53+
s.overwrite(0, alias.length, aliasPath);
54+
return path.resolve(s.toString());
55+
}
56+
}
57+
58+
return file;
3059
}
3160

3261
/**
@@ -71,7 +100,7 @@ export function importCSSPreprocess(): PreprocessorGroup {
71100
} else {
72101
out.push(remove(0, end));
73102
}
74-
const absPath = path.join(path.dirname(filename ?? ""), file);
103+
const absPath = await getAbsPath({ filename, file });
75104
deps.push(absPath);
76105
const text = (await fs.readFile(absPath)).toString();
77106
out.push(new MagicString(text, { filename: absPath }));

0 commit comments

Comments
 (0)