-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathjsx.js
68 lines (61 loc) · 1.64 KB
/
jsx.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
import path from 'path';
import fs from 'fs';
import url from 'url';
import Babel from '@babel/core';
import fetch from 'node-fetch';
import dataUrls from 'data-urls';
import {parseIdHash} from '../util.js';
const textDecoder = new TextDecoder();
const cwd = process.cwd();
export default {
async resolveId(source, importer) {
if (/^\.\//.test(source) && /^data:/.test(importer)) {
return path.join(cwd, source);
} else {
return undefined;
}
},
async load(id) {
let src;
if (/https?:/i.test(id)) {
const o = url.parse(id, true);
o.query['noimport'] = 1 + '';
id = url.format(o);
const res = await fetch(id);
src = await res.text();
} else if (/^data:/.test(id)) {
const o = dataUrls(id);
if (o) {
const {/*mimeType, */body} = o;
src = textDecoder.decode(body);
} else {
throw new Error('invalid data url');
}
} else {
const p = id.replace(/#[\s\S]+$/, '');
src = await fs.promises.readFile(p, 'utf8');
}
const {
contentId,
name,
description,
components,
} = parseIdHash(id);
const spec = Babel.transform(src, {
presets: ['@babel/preset-react'],
// compact: false,
});
let {code} = spec;
code += `
export const contentId = ${JSON.stringify(contentId)};
export const name = ${JSON.stringify(name)};
export const description = ${JSON.stringify(description)};
export const type = 'js';
export const components = ${JSON.stringify(components)};
`;
return {
code,
map: null,
};
},
};