Created
June 7, 2025 01:48
-
-
Save scarletquasar/9914617afb07a5c96dad1773b8eb4145 to your computer and use it in GitHub Desktop.
poc ts-loader for node 23+ correct importing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Keep that file in the project root and call the index with `node --loader ./ts-loader.js ./src/index.ts` | |
import { stat } from "fs/promises"; | |
import { join, dirname, isAbsolute } from "path"; | |
import { fileURLToPath, pathToFileURL } from "url"; | |
export async function resolve(specifier, context, nextResolve) { | |
if ( | |
!specifier.startsWith("file:") && | |
!specifier.startsWith("./") && | |
!specifier.startsWith("../") && | |
!specifier.startsWith("/") | |
) { | |
return nextResolve(specifier, context); | |
} | |
let baseDir = process.cwd(); | |
if (context.parentURL && context.parentURL.startsWith("file:")) { | |
baseDir = dirname(fileURLToPath(context.parentURL)); | |
} | |
let resolved; | |
try { | |
let tsFile; | |
if (specifier.startsWith("file:")) { | |
tsFile = fileURLToPath(specifier); | |
} else if (isAbsolute(specifier)) { | |
tsFile = specifier; | |
} else { | |
tsFile = join(baseDir, specifier); | |
} | |
if (!tsFile.endsWith(".ts")) { | |
tsFile += ".ts"; | |
} | |
await stat(tsFile); | |
resolved = tsFile; | |
} catch { | |
try { | |
let dir; | |
if (specifier.startsWith("file:")) { | |
dir = fileURLToPath(specifier); | |
} else if (isAbsolute(specifier)) { | |
dir = specifier; | |
} else { | |
dir = join(baseDir, specifier); | |
} | |
const indexTs = join(dir, "index.ts"); | |
await stat(indexTs); | |
resolved = indexTs; | |
} catch { | |
return nextResolve(specifier, context); | |
} | |
} | |
return { | |
url: pathToFileURL(resolved).href, | |
shortCircuit: true, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
🥉