Skip to content

Commit

Permalink
perf(resolver): stat absolute paths once in fast path
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Feb 21, 2024
1 parent aa5882a commit 3f08790
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/resolve.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, realpathSync } from "node:fs";
import { statSync } from "node:fs";
import { pathToFileURL } from "node:url";
import { joinURL } from "ufo";
import { isAbsolute, normalize } from "pathe";
Expand Down Expand Up @@ -27,7 +27,7 @@ function _tryModuleResolve(
id: string,
url: URL,
conditions: any,
): any | undefined {
): URL | undefined {
try {
return moduleResolve(id, url, conditions);
} catch (error) {
Expand All @@ -49,10 +49,17 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
}

// Skip resolve for absolute paths
if (isAbsolute(id) && existsSync(id)) {
// Resolve realPath and normalize slash
const realPath = realpathSync(fileURLToPath(id));
return pathToFileURL(realPath).toString();
if (isAbsolute(id)) {
try {
const stat = statSync(id);
if (stat.isFile()) {
return pathToFileURL(id).toString();
}
} catch (error) {
if (error.code !== "ENOENT") {
throw error;
}
}
}

// Condition set
Expand Down Expand Up @@ -82,7 +89,7 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
}
}

let resolved;
let resolved: URL | undefined;
for (const url of urls) {
// Try simple resolve
resolved = _tryModuleResolve(id, url, conditionsSet);
Expand Down Expand Up @@ -120,9 +127,8 @@ function _resolve(id: string, options: ResolveOptions = {}): string {
throw error;
}

// Resolve realPath and normalize slash
const realPath = realpathSync(fileURLToPath(resolved));
return pathToFileURL(realPath).toString();
// Normalize (TODO: simplify)
return pathToFileURL(fileURLToPath(resolved)).toString();
}

export function resolveSync(id: string, options?: ResolveOptions): string {
Expand Down

0 comments on commit 3f08790

Please sign in to comment.