-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranspiler.ts
45 lines (39 loc) · 1.13 KB
/
transpiler.ts
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
import { transform } from "@babel/core";
const componentName = 'WhatsMyNumber'
const solution = `
import React, { useState, useEffect, useCallback } from 'react'
interface Props {
}
// component which shows a input for a number
function ${componentName}(props: Props): JSX.Element {
const [value, setValue] = useState(0)
const onChange = useCallback(event => setValue(Number(event.target.value)), [])
useEffect(() => {
onChange(event)
}, [])
return (
<input type="number" value={value} onChange={onChange} />
)
}
`
const codeToCompile = `
import ReactDOMServer from 'react-dom/server'
${solution}
ReactDOMServer.renderToStaticMarkup(<${componentName} />)
`
const options = {
filename: 'file.tsx',
"presets": ["@babel/react", "@babel/typescript", ["@babel/env", { "modules": 'commonjs' }]],
}
transform(codeToCompile, options, function(err, result) {
if (err) {
console.log(`Couldn't vibe: ${err.message}`)
return
}
if (result) {
const code = `${result.code}`
console.log('code', code)
const resultHtml = eval(code)
console.log('resultHtml',resultHtml)
}
});