-
-
Notifications
You must be signed in to change notification settings - Fork 919
Expand file tree
/
Copy pathload-jsx.js
More file actions
89 lines (74 loc) · 2.15 KB
/
load-jsx.js
File metadata and controls
89 lines (74 loc) · 2.15 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
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import fs from 'node:fs/promises'
import {fileURLToPath} from 'node:url'
import {transform} from 'esbuild'
const {getFormat, load, transformSource} = createLoader()
export {getFormat, load, transformSource}
/**
* A tiny JSX loader.
*/
export function createLoader() {
return {load, getFormat, transformSource}
// Node version 17.
/**
* @param {string} href
* @param {unknown} context
* @param {Function} defaultLoad
*/
async function load(href, context, defaultLoad) {
const url = new URL(href)
if (!url.pathname.endsWith('.jsx')) {
return defaultLoad(href, context, defaultLoad)
}
const {code, warnings} = await transform(String(await fs.readFile(url)), {
format: 'esm',
loader: 'jsx',
sourcefile: fileURLToPath(url),
sourcemap: 'both',
target: 'esnext'
})
if (warnings) {
for (const warning of warnings) {
console.log(warning.location)
console.log(warning.text)
}
}
return {format: 'module', shortCircuit: true, source: code}
}
// Pre version 17.
/**
* @param {string} href
* @param {unknown} context
* @param {Function} defaultGetFormat
*/
function getFormat(href, context, defaultGetFormat) {
const url = new URL(href)
return url.pathname.endsWith('.jsx')
? {format: 'module'}
: defaultGetFormat(href, context, defaultGetFormat)
}
/**
* @param {Buffer} value
* @param {{url: string, [x: string]: unknown}} context
* @param {Function} defaultTransformSource
*/
async function transformSource(value, context, defaultTransformSource) {
const url = new URL(context.url)
if (!url.pathname.endsWith('.jsx')) {
return defaultTransformSource(value, context, defaultTransformSource)
}
const {code, warnings} = await transform(String(value), {
format: context.format === 'module' ? 'esm' : 'cjs',
loader: 'jsx',
sourcefile: fileURLToPath(url),
sourcemap: 'both',
target: 'esnext'
})
if (warnings) {
for (const warning of warnings) {
console.log(warning.location)
console.log(warning.text)
}
}
return {source: code}
}
}