-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathload.mjs
More file actions
42 lines (34 loc) · 1.08 KB
/
load.mjs
File metadata and controls
42 lines (34 loc) · 1.08 KB
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
import { createRequire } from 'module';
import { fileURLToPath } from 'url';
import { sendPort } from './ipc.mjs';
const require = createRequire(import.meta.url);
// Port used for communication between the loader and ESM modules
// https://nodejs.org/api/esm.html#globalpreload
let port;
export async function load(url, context, defaultLoad) {
const required = url.startsWith('file://') ? fileURLToPath(url) : url;
sendPort(port, { required });
try {
return await defaultLoad(url, context, defaultLoad);
} catch (error) {
if (error.code !== 'ERR_UNKNOWN_FILE_EXTENSION') throw error;
return require('get-package-type')(required).then(format => {
if (!['builtin', 'commonjs'].includes(format)) throw error;
return { format };
});
}
}
export const globalPreload = (context) => {
// Store port
port = context.port;
// Inject code to forward loader events to the parent
return `
port.on('message', (m) => {
if (process.connected) process.send(m);
}).unref();
`;
};
export const initialize = (context) => {
// Store port
port = context.port;
};