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

Put a cache in front of matchFromAbsolutePaths #227

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 17 additions & 6 deletions src/match-path-sync.ts
Expand Up @@ -52,6 +52,7 @@ export function createMatchPath(
);
}

const matchFromAbsolutePathsCache = new Map(); // This is a very hot path for most apps, so we want to cache calls into it
/**
* Finds a path from tsconfig that matches a module load request.
*
Expand All @@ -69,19 +70,29 @@ export function matchFromAbsolutePaths(
readJson: Filesystem.ReadJsonSync = Filesystem.readJsonFromDiskSync,
fileExists: Filesystem.FileExistsSync = Filesystem.fileExistsSync,
extensions: Array<string> = Object.keys(require.extensions),
mainFields: (string | string[])[] = ["main"]
mainFields: (string | string[])[] = ['main'],
): string | undefined {
const tryPaths = TryPath.getPathsToTry(
// Create stable cache keys for future invocations
const cacheKey = [
absolutePathMappings.map(mapping => `${mapping.pattern}:${mapping.paths.join('')}`),
extensions,
absolutePathMappings,
requestedModule
);
requestedModule,
].join('|');

if (matchFromAbsolutePathsCache.has(cacheKey)) {
return matchFromAbsolutePathsCache.get(cacheKey);
}

const tryPaths = TryPath.getPathsToTry(extensions, absolutePathMappings, requestedModule);

if (!tryPaths) {
matchFromAbsolutePathsCache.set(cacheKey, undefined);
return undefined;
}

return findFirstExistingPath(tryPaths, readJson, fileExists, mainFields);
const path = findFirstExistingPath(tryPaths, readJson, fileExists, mainFields);
matchFromAbsolutePathsCache.set(cacheKey, path);
return path;
}

function findFirstExistingMainFieldMappedFile(
Expand Down