-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.js
71 lines (62 loc) · 2.17 KB
/
loader.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
// loader.js
// import { resolve, extname } from 'path';
import { pathToFileURL } from 'url';
import { resolvers } from './use.mjs';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
// The `resolve` hook customizes how module URLs are resolved
export async function resolve(specifier, context, defaultResolve) {
// const { parentURL } = context;
// // You can add custom logic here to modify how modules are resolved
// if (specifier.startsWith('custom:')) {
// // Replace "custom:" specifiers with an actual path or URL
// const resolvedUrl = new URL(specifier.replace('custom:', ''), parentURL).href;
// return { url: resolvedUrl };
// }
let defaultResolveError;
try {
const resolution = await defaultResolve(specifier, context, defaultResolve);
if (resolution && resolution.url) {
return resolution;
}
} catch (error) {
defaultResolveError = error;
}
try {
const { npm } = resolvers;
const resolvedUrl = await npm(specifier, require.resolve);
return { url: pathToFileURL(resolvedUrl).href };
} catch (error) {
if (defaultResolveError) {
console.error(error);
throw defaultResolveError;
} else {
throw error;
}
}
}
// The `load` hook customizes how module code is loaded
export async function load(url, context, defaultLoad) {
// // Handle specific file extensions (e.g., custom logic for `.custom` files)
// if (extname(url) === '.custom') {
// // Return custom source code for `.custom` files
// return {
// format: 'module',
// source: `export default 'This is a .custom file';`,
// };
// }
// Fallback to default loading
return defaultLoad(url, context, defaultLoad);
}
// Optional: Transform the source code of loaded modules
export async function transformSource(source, context, defaultTransformSource) {
// const { url } = context;
// // Example: Add a comment to all JavaScript modules
// if (url.endsWith('.js')) {
// return {
// source: `// Transformed by loader.js\n${source}`,
// };
// }
// Fallback to default transformation
return defaultTransformSource(source, context, defaultTransformSource);
}