-
Notifications
You must be signed in to change notification settings - Fork 9
/
loader.js
50 lines (41 loc) · 1.85 KB
/
loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { load as loadTs, resolve as resolveTs } from 'ts-node/esm'
import * as tsConfigPaths from 'tsconfig-paths'
import { pathToFileURL, fileURLToPath } from 'url'
import path, { dirname } from 'path'
// A custom loader is used to register tsConfigPaths as well as
// run the typescript compiler via ts-node with its ESM.
// The below solution was found at https://github.com/TypeStrong/ts-node/discussions/1450#discussioncomment-1806115
const { absoluteBaseUrl, paths } = tsConfigPaths.loadConfig()
const matchPath = tsConfigPaths.createMatchPath(absoluteBaseUrl, paths)
export function resolve (specifier, ctx, defaultResolve) {
const lastIndexOfIndex = specifier.lastIndexOf('/index.js')
if (lastIndexOfIndex !== -1) {
// Handle index.js
const trimmed = specifier.substring(0, lastIndexOfIndex)
const match = matchPath(trimmed)
if (match) return resolveTs(pathToFileURL(`${match}/index.js`).href, ctx, defaultResolve)
} else if (specifier.endsWith('.js')) {
// Handle *.js
const trimmed = specifier.substring(0, specifier.length - 3)
const match = matchPath(trimmed)
if (match) return resolveTs(pathToFileURL(`${match}.js`).href, ctx, defaultResolve)
}
return resolveTs(specifier, ctx, defaultResolve)
}
// specify a custom loader for node.js extension-less files
// to get mocha binary to work with ts-node esm loader: https://github.com/nodejs/node/issues/33226
export async function load(resolvedUrl, context, defaultLoad) {
const url = new URL(resolvedUrl);
const ext = path.extname(url.pathname);
const parentDir = path
.dirname(url.pathname)
.split(path.sep)
.at(-1);
if (!ext && parentDir === 'bin') return await loadTs(resolvedUrl, {
...context,
format: 'commonjs',
});
const result = await loadTs(resolvedUrl, context, defaultLoad);
return result;
}
export { transformSource } from 'ts-node/esm'