Created
March 8, 2022 18:56
-
-
Save Ar4ys/7a6dba7f3f713a55a61b93027019a70c to your computer and use it in GitHub Desktop.
Node.js v17 ESM loader for tsconfig-paths + ts-node
This file contains 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
// @ts-check | |
import { Module } from 'node:module' | |
import { createMatchPath, loadConfig, register } from 'tsconfig-paths'; | |
export { load, getFormat, transformSource } from 'ts-node/esm.mjs' | |
import { resolve as tsNodeResolve } from 'ts-node/esm.mjs' | |
const configLoaderResult = loadConfig(); | |
let matchPath; | |
if (configLoaderResult.resultType === 'success') { | |
register(configLoaderResult) | |
matchPath = createMatchPath( | |
configLoaderResult.absoluteBaseUrl, | |
configLoaderResult.paths, | |
configLoaderResult.mainFields, | |
configLoaderResult.addMatchAll | |
); | |
} else { | |
console.warn(`${configLoaderResult.message}. tsconfig-paths will be skipped`); | |
} | |
/** | |
* @param {string} path | |
* @param {*} context | |
* @param {*} defaultResolve | |
* @returns | |
*/ | |
export async function resolve(path, context, defaultResolve) { | |
if (matchPath && !path.startsWith('node:') && !Module.builtinModules.includes(path)) { | |
const matchedPath = matchPath(path); | |
path = matchedPath ?? path | |
} | |
return tsNodeResolve.call(this, path, context, defaultResolve); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment