Skip to content

Commit

Permalink
refactor: Optimize resolve hook
Browse files Browse the repository at this point in the history
  • Loading branch information
Septh committed Jun 1, 2024
1 parent d903b6e commit e61ce0b
Showing 1 changed file with 6 additions and 10 deletions.
16 changes: 6 additions & 10 deletions source/esm-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const initialize: InitializeHook<NodeJS.InitializeHookData> = data => {
defaultModuleType = data.defaultModuleType
}

export const resolve: ResolveHook = async (specifier, context, nextResolve) => {
export const resolve: ResolveHook = (specifier, context, nextResolve) => {
// when run with `ts-run <script>` or `node path/to/index.js <script>`,
// we need to resolve the entry point specifier relative to process.cwd()
// because otherwise Node would resolve it relative to our own index.js.
Expand All @@ -25,18 +25,14 @@ export const resolve: ResolveHook = async (specifier, context, nextResolve) => {
parentURL: undefined
}

if (path.isAbsolute(specifier))
if (path.isAbsolute(specifier)) {
// On Windows, absolute paths must be valid file:// URLs.
specifier = pathToFileURL(specifier).href
}
else if (/^\w/.test(specifier))
specifier = './' + specifier

return {
...await nextResolve(specifier, context),
shortCircuit: true
}
}

// Normal operation otherwise.
return nextResolve(specifier, context)
}

Expand All @@ -51,9 +47,9 @@ async function nearestPackageType(file: string): Promise<NodeJS.ModuleType> {
const pkgFile = path.join(current, 'package.json')
let format = pkgTypeCache.get(pkgFile)
if (!format) {
format = await readFile(pkgFile, 'utf-8')
format = await readFile(pkgFile)
.then(data => {
const { type } = JSON.parse(data) as PackageJson
const { type } = JSON.parse(data.toString()) as PackageJson
return type === 'module' || type === 'commonjs'
? type
: unknownType
Expand Down

0 comments on commit e61ce0b

Please sign in to comment.