This is the 12th day of my participation in Gwen Challenge.

preface

The code generator is the final step in template compilation and is used to convert the AST into the content of the rendering function, which can be called a code string.

<div id="el">Hello {{name}}</div>
Copy the code

In the template above, the resulting code string looks like this:

`with(this){return _c("div", {attrs: {"id": "el"}}, [_v("Hello " _s(name))])}`
Copy the code

The _c in the code string is actually an alias for createElement. CreateElement is a method provided in the virtual DOM that creates a virtual node with three parameters:

  • Tag name
  • A data object that contains attributes associated with the template
  • Child node list

By calling the createElement method, we get a VNode.

Generate code strings through the AST

Generating code strings is a recursive process that processes each AST node from top to bottom.

Principles of code generators

There are different types of nodes, such as element nodes, text nodes, and comment nodes. Different types of nodes are generated in different ways.

Element nodes

Generating element nodes is essentially generating a _c function call string

function genElement(el, state){
    const data = el.plain ? undefined : genData(el, state);
    
    const children = genChildren(el, state);
    
    code = `_c('${el.tag}'${
        data ? `, ${data}` : ' '
    }${
        children ? `,${children}`:' '
    }) `
    return code;
}
Copy the code

Text node

Generating a text node is easy; we simply place the text in the _v function argument

function genText(text){
    return `_v(${text.type === 2 ? text.expression : JSON.stringify(text.text)}) `
}
Copy the code

Why does text need the json.stringify method?

Because json.stringify can wrap a layer of strings around text, for example:

JSON.stringify('Hello') // "'Hello'"
Copy the code

Comment node

function genComment(comment){
    return `_e(The ${JSON.stringify(comment.text)}) `
}
Copy the code

conclusion

In this article, we learned about the functions and internals of code generators, which are essentially the process of string concatenation. The recursive AST is used to generate the string. The root node is generated first, and then after the string of the child node is generated, it is spliced into the parameters of the root node, and the children of the child node are spliced into the parameters of the child node, and so on, layer by layer, until finally spliced into a complete string.