-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathloader.mjs
More file actions
46 lines (40 loc) · 1.28 KB
/
loader.mjs
File metadata and controls
46 lines (40 loc) · 1.28 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
43
44
45
46
import { extname } from 'path';
const requiredCode = `import * as React from 'react';`;
const css = new URL('mocks/css.mjs', import.meta.url).href;
/**
*
* This hook intercepts module resolution, allowing us to handle
* CSS/SCSS files in a custom way. Instead of actually loading the CSS,
* we short-circuit the resolution and return a mock module.
*
* @type {import('node:module').ResolveHook}
*/
export async function resolve(specifier, ctx, nextResolve) {
const ext = extname(specifier);
if (ext === '.css' || ext === '.scss') {
// For CSS/SCSS, return the mock CSS module and skip default resolution.
return {
format: 'module',
url: css,
shortCircuit: true,
};
}
return nextResolve(specifier);
}
/**
*
* This hook is used to modify the source of JSX/TSX files on the fly.
* We prepend the necessary React import to ensure React is available,
* which is required for JSX to work without explicitly importing React.
*
* @type {import('node:module').LoadHook}
*/
export async function load(url, ctx, nextLoad) {
const ext = extname(url);
const result = await nextLoad(url, ctx);
if (ext === '.jsx' || ext === '.tsx') {
// Ensure React is in scope for JSX transforms.
result.source = requiredCode + result.source;
}
return result;
}