-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathbuiltin-named-exports-loader.mjs
59 lines (50 loc) · 1.29 KB
/
builtin-named-exports-loader.mjs
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
import module from 'module';
const GET_BUILTIN = `$__get_builtin_hole_${Date.now()}`;
export function globalPreload() {
return `Object.defineProperty(globalThis, ${JSON.stringify(GET_BUILTIN)}, {
value: (builtinName) => {
return getBuiltin(builtinName);
},
enumerable: false,
configurable: false,
});
`;
}
export async function resolve(specifier, context, next) {
const def = await next(specifier, context);
if (def.url.startsWith('node:')) {
return {
shortCircuit: true,
url: `custom-${def.url}`,
importAssertions: context.importAssertions,
};
}
return def;
}
export function load(url, context, next) {
if (url.startsWith('custom-node:')) {
const urlObj = new URL(url);
return {
shortCircuit: true,
source: generateBuiltinModule(urlObj.pathname),
format: 'module',
};
}
return next(url);
}
function generateBuiltinModule(builtinName) {
const builtinInstance = module._load(builtinName);
const builtinExports = [
...Object.keys(builtinInstance),
];
return `\
const $builtinInstance = ${GET_BUILTIN}(${JSON.stringify(builtinName)});
export const __fromLoader = true;
export default $builtinInstance;
${
builtinExports
.map(name => `export const ${name} = $builtinInstance.${name};`)
.join('\n')
}
`;
}