Skip to content

Instantly share code, notes, and snippets.

@wesleybliss
Created April 4, 2025 20:10
Show Gist options
  • Save wesleybliss/e37a4cada3b061c1057f2c83f6042cf7 to your computer and use it in GitHub Desktop.
Save wesleybliss/e37a4cada3b061c1057f2c83f6042cf7 to your computer and use it in GitHub Desktop.
Custom ESM loader
import { resolve as resolvePath } from 'path'
import { fileURLToPath } from 'url'
import { stat } from 'fs/promises'
const loggingEnabled = false
const consoleLog = (verb, ...args) => loggingEnabled && console[verb](...args)
const log = {
d: (...args) => consoleLog('log', ...args),
i: (...args) => consoleLog('info', ...args),
w: (...args) => consoleLog('warn', ...args),
e: (...args) => consoleLog('error', ...args),
}
// Log to confirm loader is loaded
log.d('Loader initialized')
const aliases = {
'@': 'src',
}
// List of extensions to try, in order of preference
const extensions = [
'.js',
'.mjs',
'.json',
'.node',
]
export async function resolve(specifier, context, nextResolve) {
log.d(`Resolving specifier: ${specifier}`)
// Check if the specifier matches an alias
for (const [alias, basePath] of Object.entries(aliases)) {
if (specifier.startsWith(alias)) {
let relativePath = specifier.slice(alias.length)
if (relativePath.startsWith('/'))
relativePath = relativePath.slice(1)
const fullPathBase = resolvePath(fileURLToPath(new URL('.', import.meta.url)), basePath, relativePath)
log.d(`Alias matched: ${alias}, Base path: ${fullPathBase}`)
// Try each extension
for (const ext of extensions) {
const fullPath = fullPathBase.endsWith(ext) ? fullPathBase : (fullPathBase + ext)
log.d(`Trying: ${fullPath}`)
try {
const stats = await stat(fullPath)
if (stats.isFile()) {
log.d(`Resolved to: ${fullPath}`)
return { url: `file://${fullPath}`, shortCircuit: true }
}
} catch (e) {
continue
}
}
// Try index files in the directory
const indexPathBase = resolvePath(fullPathBase, 'index')
for (const ext of extensions) {
const indexFullPath = indexPathBase + ext
log.d(`Trying index: ${indexFullPath}`)
try {
const stats = await stat(indexFullPath)
if (stats.isFile()) {
log.d(`Resolved to index: ${indexFullPath}`)
return { url: `file://${indexFullPath}`, shortCircuit: true }
}
} catch (e) {
continue
}
}
throw new Error(`Cannot find module '${specifier}' with any supported extension`)
}
}
// Fallback to default resolver if no alias matches
log.d(`No alias match, passing to default: ${specifier}`)
return nextResolve(specifier, context)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment