/
module-types.js
57 lines (51 loc) 路 1.35 KB
/
module-types.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
import { isAsync, waitFor } from "../../gensync-utils/async";
import type { Handler } from "gensync";
let import_;
try {
// Node < 13.3 doesn't support import() syntax.
import_ = require("./import").default;
} catch {}
export default function* loadCjsOrMjsDefault(
filepath: string,
asyncError: string,
): Handler<mixed> {
switch (guessJSModuleType(filepath)) {
case "cjs":
return loadCjsDefault(filepath);
case "unknown":
try {
return loadCjsDefault(filepath);
} catch (e) {
if (e.code !== "ERR_REQUIRE_ESM") throw e;
}
case "mjs":
if (yield* isAsync()) {
return yield* waitFor(loadMjsDefault(filepath));
}
throw new Error(asyncError);
}
}
function guessJSModuleType(path: string): "cjs" | "mjs" | "unknown" {
switch (path.slice(-4)) {
case ".cjs":
return "cjs";
case ".mjs":
return "mjs";
default:
return "unknown";
}
}
function loadCjsDefault(filepath: string) {
const module = (require(filepath): mixed);
return module?.__esModule ? module.default || undefined : module;
}
async function loadMjsDefault(filepath: string) {
if (!import_) {
throw new Error(
"Internal error: Native ECMAScript modules aren't supported" +
" by this platform.\n",
);
}
const module = await import_(filepath);
return module.default;
}