-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
85 lines (67 loc) · 2.32 KB
/
index.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { moduleResolve } from 'import-meta-resolve';
const EXTENSIONS = ['.js', '.mjs', '.cjs'];
function resolveToFileURL(...paths) {
return pathToFileURL(resolve(...paths));
}
async function tryImport(moduleId) {
try {
return await import(moduleId);
} catch {}
}
async function importFrom(fromDirectory, moduleId) {
let loadedModule;
if (/^(\/|\.\.\/|\.\/)/.test(moduleId)) {
// If moduleId begins with '/', '../', or './', try to
// resolve manually so we can support extensionless imports
// - https://nodejs.org/api/modules.html#file-modules
const localModulePath = resolveToFileURL(fromDirectory, moduleId);
// Try to resolve exact file path
loadedModule = await tryImport(localModulePath);
if (!loadedModule) {
// Try to resolve file path with added extensions
for (const ext of EXTENSIONS) {
// eslint-disable-next-line no-await-in-loop
loadedModule = await tryImport(`${localModulePath}${ext}`);
if (loadedModule) {
break;
}
}
}
} else {
// Let `import-meta-resolve` deal with resolving packages & import maps
// - https://nodejs.org/api/modules.html#loading-from-node_modules-folders
// - https://nodejs.org/api/packages.html#subpath-imports
try {
const parentModulePath = resolveToFileURL(fromDirectory, 'noop.js');
loadedModule = await import(moduleResolve(moduleId, parentModulePath, new Set(['node', 'import'])));
} catch {}
// Support for extensionless subpath package access (not subpath exports)
if (!loadedModule && !moduleId.startsWith('#')) {
// Try to resolve file path with added extensions
for (const ext of EXTENSIONS) {
try {
const parentModulePath = resolveToFileURL(fromDirectory, 'noop.js');
// eslint-disable-next-line no-await-in-loop
loadedModule = await import(moduleResolve(`${moduleId}${ext}`, parentModulePath, new Set(['node', 'import'])));
} catch {}
if (loadedModule) {
break;
}
}
}
}
if (!loadedModule) {
const error = new Error(`Cannot find module '${moduleId}'`);
error.code = 'MODULE_NOT_FOUND';
throw error;
}
return loadedModule.default;
}
importFrom.silent = async function (fromDirectory, moduleId) {
try {
return await importFrom(fromDirectory, moduleId);
} catch {}
};
export default importFrom;