Skip to content

Instantly share code, notes, and snippets.

@Ar4ys
Created March 8, 2022 18:56
Show Gist options
  • Save Ar4ys/7a6dba7f3f713a55a61b93027019a70c to your computer and use it in GitHub Desktop.
Save Ar4ys/7a6dba7f3f713a55a61b93027019a70c to your computer and use it in GitHub Desktop.
Node.js v17 ESM loader for tsconfig-paths + ts-node
// @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