Template Compilation: parse, transform, and generate

Understand the three stages of Vue 3 template compilation and how patch flags and static hoisting reduce runtime work.

🎯 Introduction

In the Vue 3 course, we wrote many <template> blocks containing familiar HTML structures and {{ }} interpolations. Yet browsers do not understand this template syntax. What Vue actually executes is a render function: an ordinary JavaScript function that returns virtual DOM.

How does a template become a render function? That translation is template compilation, the subject of this article. We will follow the compiler through each step.

In the previous article on virtual DOM and patching, we saw that the vnodes returned by render functions carry patch flags, enabling targeted comparisons during updates. The compiler produces those flags.

By the end, you will be able to:

  • Explain the parse, transform, and generate stages.
  • Read the AST produced from a simple template.
  • Identify where optimizations such as patch flags and static hoisting are applied.
  • Explain why work that can be done at compile time should not be deferred to runtime.

The source excerpts use Vue 3.5.x from the GitHub vuejs/core monorepo, primarily packages/compiler-core.


🧱 Compilation Overview: Three Stages

How does a template string become a render function? Let's start with the overall flow before examining each stage.

The main entry point is baseCompile, whose core logic has three steps:

// Simplified from baseCompile in packages/compiler-core/src/compile.ts
function baseCompile(template, options) {
    // 1. Parse the template string into an AST (a tree of objects, explained below)
    const ast = baseParse(template);

    // 2. Visit AST nodes, transform them, and annotate optimizations
    transform(ast, options);

    // 3. Generate render function source code from the processed AST
    return generate(ast, options);
}

Each stage has a distinct responsibility:

  • parse reads the template and produces an AST.
  • transform processes AST nodes, flags dynamic content, and hoists static nodes.
  • generate emits render function code from the processed AST.

Let's examine them in order.


🧱 parse: From Template to AST

The first step is to understand the template. But a template is just a sequence of characters. How does the compiler recognize its structure?

AST stands for abstract syntax tree. It represents the template's structure as a tree of objects. Each node records its type and content, with nested children preserving the template's hierarchy.

The parser scans the template from start to finish. When it encounters tags, attributes, or text, it creates corresponding nodes in the tree. For <div>{{ count }}</div>, the result looks roughly like this, with source locations and other secondary fields omitted:

// Schematic AST after parsing
{
    type: 0, // ROOT: contains the entire template
    children: [
        {
            type: 1, // ELEMENT: represents an element
            tag: 'div', // Tag name
            props: [], // Element attributes; none here
            children: [
                {
                    type: 5, // INTERPOLATION: represents {{ }}
                    content: {
                        type: 4, // SIMPLE_EXPRESSION: an expression node
                        content: 'count', // The expression is count
                    },
                },
            ],
        },
    ],
}

The structure maps directly to the template:

  • ROOT contains the whole template.
  • The ELEMENT node for <div> records its tag and attributes.
  • The INTERPOLATION node for {{ count }} contains an expression node whose content is count.

You do not need to memorize the numeric type values. The source defines them in NodeTypes: 1 represents an element, 5 an interpolation, and so on. Look them up as needed. Once this tree exists, subsequent stages operate on objects rather than the original string. That is the purpose of parsing: turn characters into structure.


🧱 transform: Transformations and Optimization Annotations

After parsing, the compiler identifies what can change and what stays fixed, which has a substantial effect on performance. The transform stage visits each AST node—an operation called traversal—and runs built-in processing logic. Two tasks are central here.

First, annotate dynamic nodes with patch flags.

A patch flag identifies which parts of a node may change during future updates. The renderer can then check those parts and skip the rest.

{{ count }} references data that may change. The compiler recognizes this and flags the containing div:

// Conceptually, transformation adds a patchFlag to the div node
{
    type: 1,
    tag: 'div',
    patchFlag: 1, // TEXT: only this node's text is dynamic
    children: [/* ... */],
}

The flag means future updates only need to compare text, without checking attributes or the child structure. These annotations enable the targeted comparisons discussed in the previous article.

Second, move static nodes out of the render function (static hoisting).

A fully static node such as <p>Static text</p> never changes. The transform stage moves its creation code outside the render function. That static vnode can then be created once and reused across subsequent renders.

Both techniques follow the same principle: do at compile time what would otherwise require runtime work. A template is a fixed string, so the compiler can identify dynamic and static content ahead of time. Recording those conclusions saves the runtime from repeating the analysis.

This focus on necessary work appears throughout Vue 3: reactivity tracks data that is actually used, and updates target nodes that change. Recognizing the idea is enough; there is no need to memorize it.

🧱 generate: Emitting the Render Function

Once the annotations are ready, the final stage turns the processed AST into render function code. Let's examine the output.

For <div>{{ count }}</div>, the generated code looks roughly like this:

// Simplified generate output for teaching
function render(_ctx, _cache) {
    // _ctx is the component context; _ctx.count corresponds to {{ count }}
    // _toDisplayString converts the value into display text
    // The final 1 is the patch flag added during transformation: dynamic text only
    return _openBlock(), _createElementBlock('div', null, _toDisplayString(_ctx.count), 1 /* TEXT */);
}

The key argument is 1 /* TEXT */: the annotation from the transform stage is now emitted into the code. The patching logic from the previous article uses this flag to compare only text. The /* TEXT */ comment is for readers and does not affect runtime behavior.

Now consider a template with a static node:

<div>
    <p>Static text</p>
    <p>{{ count }}</p>
</div>

Its generated code looks roughly like this:

// Simplified generate output for teaching
// Hoist the static node outside render so it is created once
const _hoisted_1 = _createElementVNode('p', null, 'Static text', -1 /* HOISTED */);

function render(_ctx, _cache) {
    return (
        _openBlock(),
        _createElementBlock('div', null, [
            _hoisted_1, // Reuse the static node instead of recreating it
            _createElementVNode('p', null, _toDisplayString(_ctx.count), 1 /* TEXT */), // Dynamic node with a patch flag
        ])
    );
}

Notice that _hoisted_1 is defined outside the render function. This is static hoisting in action. Subsequent renders reference the existing vnode rather than creating it again, and largely avoid comparing it.


🧱 What Compilation Optimizations Save

How much work do these flags and hoists avoid? Let's connect them to the previous articles.

  • Static hoisting creates static vnodes once and reuses them on later renders, avoiding repeated creation and comparison.
  • Patch flags + Blocks: a Block collects dynamic nodes, as described in the previous article. Flagged dynamic nodes are gathered into a list. Updates iterate that list, compare the flagged parts, and skip static subtrees.

This is one important reason Vue 3 updates can outperform Vue 2. In the comparison presented here, Vue 2 traverses the old and new vnode trees within a component, including static nodes. Vue 3 moves the analysis of dynamic content to compile time, narrowing the comparisons needed at runtime. The mechanism explains the improvement more clearly than a benchmark number alone.


⚡ Comparing Compilation with Vue 2

If you studied template compilation in the Vue 2 source code course, the overall flow will look familiar: parse, transform, generate. Vue 2 calls the middle optimization step optimize, focusing on static nodes. The difference lies in the work performed during transformation. Vue 3's Block mechanism supports patch flags, dynamic-node collection, and static hoisting annotations; Vue 2's optimizer focuses on static roots, offering a more limited optimization strategy. The compiler is therefore a major part of Vue 3's performance improvements.


❓ Questions and Answers

Q1: When does compilation happen?

There are two cases. Build-time compilation is the usual approach: @vitejs/plugin-vue or vue-loader compiles templates in .vue files during the build, and the browser receives compiled code. With runtime compilation, a template string is passed to Vue in the browser and compiled by its bundled compiler. Runtime compilation increases bundle size and adds compilation work to the initial render, so most applications compile at build time.

Q2: What is the difference between runtime-only and full builds?

The runtime-only build omits the compiler, making it smaller, but requires precompiled templates. The full build includes the compiler and can compile template strings in the browser. Vite and Webpack setups normally use the runtime-only build, which works with templates in .vue files because the build tools compile them. To compile a template string at runtime, use the full build.

Q3: Can I inspect the output of build-time compilation?

Yes. Vue's official Vue Template Explorer lets you enter a template on the left and inspect the generated render function on the right. It is useful for experimenting with this article's examples. You can also search local build output for helpers such as _createElementBlock to find compiled code.

Q4: If handwritten render functions are more flexible, why are templates usually preferred?

Handwritten render functions provide the full expressive power of JavaScript for complex rendering, including JSX use cases. However, they can reduce readability and maintainability, and require you to consider optimizations such as patch flags and static hoisting yourself. Templates balance developer experience and performance well. Use handwritten render functions when templates cannot express the required behavior.


🧪 Exercise

Without referring to the explanation above, write the compiled render function for this template. A simplified teaching version using helpers such as _createElementVNode is sufficient:

<div class="box">
    <span>Welcome</span>
    <span>{{ name }}</span>
</div>

Hoist the static <span>Welcome</span> outside the render function, and give the dynamic interpolation the 1 /* TEXT */ patch flag.

// Your code here: define the hoisted static vnode first

function render(_ctx, _cache) {
    // Your code here: return the vnode for the root div
}

Compare your result with the generate example above. Is the static node outside the function? Does the dynamic node have the correct patch flag? You can also paste the template into Vue Template Explorer to compare your answer with the official compiler output.


🎉 You have completed the main path through the Vue 3 source code course! We followed mounting from createApp, explored reactive and effect, examined scheduler timing and targeted patching, and finally saw how templates become render functions. Together, these form the core flow behind the Vue you use every day. The course ends here, but there is much more to explore: component updates, keep-alive, and Teleport are just a few examples. Take the source-reading techniques from these eight articles and continue exploring vuejs/core!