-
Notifications
You must be signed in to change notification settings - Fork 19
/
transpiler.js
57 lines (47 loc) · 1.76 KB
/
transpiler.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
import parse from './vdom-parser.js'
function parseHtmlComponent(html) {
const templateMatch = html.match(/<template[^>]*>([\s\S]*)<\/template>/m)
const scriptMatch = html.match(/<script[^>]*>([\s\S]*)<\/script>/m)
const styleMatch = html.match(/<style[^>]*>([\s\S]*)<\/style>/m)
const template = templateMatch ? templateMatch[1].trim() : ''
const script = scriptMatch ? scriptMatch[1].trim() : ''
const style = styleMatch ? styleMatch[1].trim() : ''
return { template, script, style }
}
function generateFileContent({ dom, importPath, baseClassName, version, preScript = '', preStyle = '' }) {
return `
// Lego version ${version}
import { h, Component } from '${importPath}'
class ${baseClassName} extends Component {
${dom.template.trim() ? `get vdom() {
return ({ state }) => ${parse(dom.template.trim())}
}` : ''}
${dom.style.trim() || preStyle ? `get vstyle() {
return ({ state }) => h('style', {}, \`
${preStyle}
${dom.style.trim()}
\`)}` : ''}
}
${preScript}
${dom.script.trim() || `export default class extends ${baseClassName} {}`}
`
}
function camelCase(name) {
return name.split('-').map(c => c.slice(0,1).toUpperCase() + c.slice(1)).join('')
}
function createComponent({ html, name, importPath, baseClassName, preScript, preStyle, version }) {
const dom = parseHtmlComponent(html)
const content = generateFileContent({ dom, importPath, baseClassName, preScript, preStyle, version })
return { name, content }
}
function generateIndex(fileNames) {
return fileNames.map((fileName) => {
const className = camelCase(fileName)
return [
`import ${className} from './${fileName}.js'`,
`customElements.define('${fileName}', ${className})`
].join('\n')
})
.join('\n\n')
}
export { createComponent, generateIndex }