-
Notifications
You must be signed in to change notification settings - Fork 9
/
test-exp-loader.js
58 lines (48 loc) · 1.86 KB
/
test-exp-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
// https://jestjs.io/docs/ecmascript-modules
// https://github.com/nodejs/node/discussions/41711
import fs from 'fs';
import path from 'path';
import { load as experimentalLoadJsx, resolve as experimentalResolveJsx } from './src/jsx-loader.js';
import { load as experimentalLoadTs, resolve as experimentalResolveTs } from './src/ts-loader.js';
export async function load(url, context, defaultLoad) {
const ext = path.extname(url);
if (ext === '') {
return loadBin(url, context, defaultLoad);
} else if (ext === '.jsx') {
return experimentalLoadJsx(url, context, defaultLoad);
} else if (ext === '.ts') {
return experimentalLoadTs(url, context, defaultLoad);
} else if (ext === '.css') {
return {
format: 'module',
shortCircuit: true,
source: `const css = \`${(await fs.promises.readFile(new URL(url), 'utf-8')).replace(/\r?\n|\r/g, ' ').replace(/\\/g, '\\\\')}\`;\nexport default css;`
};
}
return defaultLoad(url, context, defaultLoad);
}
export function resolve(specifier, context, defaultResolve) {
const ext = path.extname(specifier);
if (ext === '.jsx') {
return experimentalResolveJsx(specifier, context, defaultResolve);
} else if (ext === '.ts') {
return experimentalResolveTs(specifier, context, defaultResolve);
} else {
return defaultResolve(specifier, context, defaultResolve);
}
}
async function loadBin(url, context, defaultLoad) {
const dirs = path.dirname(url.replace(/[A-Z]:\//g, '')).split('/');
const parentDir = dirs.at(-1);
const grandparentDir = dirs.at(-3);
let format;
if (parentDir === 'bin' && grandparentDir === 'node_modules') {
const libPkgUrl = new URL('../package.json', url);
const { type } = await fs.promises.readFile(libPkgUrl).then(JSON.parse);
format = type === 'module' ? 'module' : 'commonjs';
}
return defaultLoad(url, {
...context,
format
});
}