The code generation phase ends up generating a string, which is then converted to the Render Function using new Function.

Generation context

  1. CreateCodegenContext (ast, options) generates and initializes the context, and provides the implementation of helper, push, Indent, deindent, and newLine methods.
    • Helper: return packages/compiler – core/SRC/runtimeHelpers helperNameMap corresponding to the value of the ts
    • Push: context.code appends (the first argument); Update cursor position; If the second argument exists, create a mapping between the original location and the new location
    • Indent: Newline and indent context.indentLevel, context.indentLevel + 1
    • Deindent :(newline or not, depending on parameters)context.indentLevel minus 1
    • NewLine: newLine and indent context.indentLevel * 2 Spaces
  2. If the onContextCreated method is defined in options, onContextCreated(Context) is called.

preambles

If setup() is inline, preambleContext is reassigned to createCodegenContext(ast, options); Otherwise, use context assignment.

  • GenModulePreamble (AST, preambleContext, genScopeId, isSetupInlined) –> genImports, genHoists;
  • Otherwise, genFunctionPreamble(AST, preambleContext) –> helpers methods, genHoists.

The main difference between them

  • In the generated Preamble, imports and exports use import/export and require/return
  • _ctx. Xx and with the (this) xx} {

The final result is the code before Export Function Render

binding optimizations

constoptimizeSources = options.bindingMetadata && ! options.inline ?`, $props, $setup, $data, $options`
      : ` `
Copy the code

That’s what we see all the time

enter render function

Construct the render function, which is the more critical two steps

  • GenAssets (ast.ponents, ‘Component ‘, context), genAssets(ast.directives, ‘directive’, Context generates component and directive parsing expressions
  • Recursively genNode(ast.codegenNode, context) generates VNode nodes. CreateVNode, createCommentVNode, createBlock, openBlock, toDisplayString, etc.

This converts the AST into a render function string.