-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (37 loc) · 1.05 KB
/
index.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
const { getOptions } = require('loader-utils')
const buble = require('buble')
const matter = require('gray-matter')
const stringifyObject = require('stringify-object')
const escapeTemplateString = code =>
code.replace(/`/g, '\\`').replace(/\$/g, '\\$')
module.exports = async function(src) {
const callback = this.async()
const opts = getOptions(this)
const { content, data } = matter(src)
const parsed = buble.transform(content).code
const scope = opts.scope
? opts.scope
: data.scope
? data.scope
: 'const scope = {}'
const code = `
import React from 'react'
${scope}
const keys = Object.keys(scope)
const values = keys.map(key => scope[key])
const Component = new Function(
'React',
...keys,
\`return props =>
React.createElement(React.Fragment, null,
${parsed}
)
\`
)(React, ...values)
export const jsx = \`${escapeTemplateString(content)}\`
export { scope }
Component.defaultProps = ${stringifyObject(data)}
export default Component
`
return callback(null, code)
}