Template literals come in handy for code generation

The task

Provided that I am working to transform a Vue-like DSL to normal HTML.

<div>hello world</div>
<div>hello world</div>
function generate(ast){
// ...
return `<${ast.tag}>${ast.text}</${ast.tag}>`
}
<div>{{ msg }}</div>
`<div>` + msg + '</div>'

Tagged template

There are 3 kinds of things we have to handle

  1. Hand-written characters like <, />
  2. Strings in the generated code like ast.tag
  3. Expressions in the generated code like ast.binding
  • literals is an array that contains all hand-written literal strings
  • exps is an array that contains all occurred variables
  1. wrap literal strings with quotes "
  2. wrap or not wrap the variables with quotes based on their type
  3. concatenate them with plus sign +

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store