forked from rockcarver/frodo-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.ts
44 lines (36 loc) · 1.3 KB
/
loader.ts
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
import { builtinModules } from 'node:module';
import { dirname } from 'path';
import { cwd } from 'process';
import { fileURLToPath, pathToFileURL } from 'url';
import { promisify } from 'util';
import resolveCallback from 'resolve/async.js';
const resolveAsync = promisify(resolveCallback);
const baseURL = pathToFileURL(cwd() + '/').href;
export async function resolve(specifier, context, next) {
const { parentURL = baseURL } = context;
if (specifier.startsWith('node:') || builtinModules.includes(specifier)) {
return next(specifier, context);
}
// `resolveAsync` works with paths, not URLs
if (specifier.startsWith('file://')) {
specifier = fileURLToPath(specifier);
}
const parentPath = fileURLToPath(parentURL);
let url;
try {
const resolution = await resolveAsync(specifier, {
basedir: dirname(parentPath),
// For whatever reason, --experimental-specifier-resolution=node doesn't search for .mjs extensions
// but it does search for index.mjs files within directories
extensions: ['.js', '.json', '.node', '.mjs'],
});
url = pathToFileURL(resolution).href;
} catch (error) {
if (error.code === 'MODULE_NOT_FOUND') {
// Match Node's error code
error.code = 'ERR_MODULE_NOT_FOUND';
}
throw error;
}
return next(url, context);
}