Skip to content

Commit

Permalink
fix(register): extension-aware module resolution and format handling
Browse files Browse the repository at this point in the history
  • Loading branch information
cm-ayf committed Sep 2, 2023
1 parent 8e44271 commit e34f006
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions packages/register/esm.mts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,16 @@ const host: ts.ModuleResolutionHost = {
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
}
const EXTENSIONS: string[] = [ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Mts]

export const resolve: ResolveFn = async (specifier, context, nextResolve) => {
// entrypoint
if (!context.parentURL) {
return { format: 'ts', url: specifier, shortCircuit: true }
return {
format: EXTENSIONS.some((ext) => specifier.endsWith(ext)) ? 'ts' : undefined,
url: specifier,
shortCircuit: true,
}
}

// import/require from external library
Expand All @@ -51,16 +56,23 @@ export const resolve: ResolveFn = async (specifier, context, nextResolve) => {
moduleResolutionCache,
)

// import from local project to local project
if (resolvedModule && !resolvedModule.isExternalLibraryImport) {
// import from local project to local project TS file
if (
resolvedModule &&
!resolvedModule.resolvedFileName.includes('/node_modules/') &&
EXTENSIONS.includes(resolvedModule.extension)
) {
return {
format: 'ts',
url: pathToFileURL(resolvedModule.resolvedFileName).href,
shortCircuit: true,
}
}

// import from local project to external library (or unknown something)
// import from local project to either:
// - something TS couldn't resolve
// - external library
// - local project non-TS file
return nextResolve(specifier)
}

Expand Down

0 comments on commit e34f006

Please sign in to comment.