Template Compilation: From template to Render Function
🎯 Introduction
In the Vue 2 course, we used {{ message }} and v-for repeatedly. Vue does not execute template syntax directly: it executes render functions. Template compilation performs the conversion between them.
By the end of this article, you will be able to explain how a template such as <div>{{ message }}</div> becomes a render function through parse, optimize, and generate, and how the full and runtime-only builds differ.
🗺 Overview: Three Compilation Stages
The compiler entry point is src/compiler/index.js. Its core logic fits in three lines, simplified here without Flow type annotations:
// Simplified from src/compiler/index.js
export const createCompiler = createCompilerCreator(function baseCompile(template, options) {
// 1. parse: template string → AST
const ast = parse(template.trim(), options);
// 2. optimize: mark static nodes
optimize(ast, options);
// 3. generate: AST → render function code string
const code = generate(ast, options);
return {
ast,
render: code.render,
};
});
Each stage has a distinct role:
- parse: parse the template string into an AST (abstract syntax tree).
- optimize: traverse the AST and mark static nodes to optimize subsequent updates.
- generate: convert the AST into a code string such as
_c('div', ...), then usenew Functionto create a render function.
Think of translating an article: first understand its structure (parse), then identify fixed passages that need no repeated translation (optimize), and finally write the translated text (generate).
🧱 parse: Template → AST
The parser in src/compiler/parser/index.js spans hundreds of lines, but its central idea is simple: scan the template string from beginning to end with regular expressions, handling start tags, attributes, end tags, and text while using a stack to maintain parent-child relationships.
Here is the simplified process:
// Simplified outline of src/compiler/parser/index.js
function parse(template) {
const stack = []; // Track the current nesting level
let root; // AST root node
while (template) {
if (template starts with an end tag) {
// For </div>, pop the stack: this element is complete
stack.pop();
} else if (template starts with a start tag) {
// For <div id="app">, create an element node
const element = { type: 1, tag: 'div', attrsList: [...], children: [] };
if (!root) root = element;
// Add it to the stack top's children, then push it onto the stack
stack.push(element);
} else {
// Text: create a text node under the current parent
// Text with {{}} has type 2; plain text has type 3
}
// Remove the processed segment from template and continue
}
return root;
}
The stack remembers the current parent: a start tag pushes an element, an end tag pops it, and the top is the parent currently being parsed.
Three AST Node Types
The parser distinguishes three kinds of AST nodes with a type field:
| type | Meaning | Example |
|---|---|---|
| 1 | Element node | <div>, <p> |
| 2 | Text node containing an expression | {{ message }} |
| 3 | Plain text node | hello |
An Example Template AST
Template:
<div id="app">
<p>{{ message }}</p>
hello
</div>
The corresponding AST looks roughly like this:
{
type: 1,
tag: 'div',
attrsList: [{ name: 'id', value: 'app' }],
children: [
{
type: 1,
tag: 'p',
children: [
{ type: 2, expression: '_s(message)', text: '{{ message }}' },
],
},
{ type: 3, text: 'hello' },
],
}
The AST is an ordinary tree of JavaScript objects. Template nesting becomes nested children arrays, and nodes record tags, attributes, text, or expressions.
✨ optimize: Mark Static Nodes
The optimizer in src/compiler/optimizer.js recursively traverses the AST and marks nodes that do not depend on reactive data with static: true.
A static node's content does not change when data changes. For example, <p>hello</p> stays the same regardless of changes to message.
Here is the simplified core logic:
// Simplified from src/compiler/optimizer.js
function optimize(root) {
markStatic(root);
}
function markStatic(node) {
// Plain text and elements without dynamic bindings are static
node.static = isStatic(node);
if (node.type === 1) {
for (const child of node.children) {
markStatic(child);
// A dynamic child makes its parent non-static
if (!child.static) node.static = false;
}
}
}
function isStatic(node) {
if (node.type === 2) return false; // Expression text is dynamic
if (node.type === 3) return true; // Plain text is static
// Elements must have no v-if, v-for, dynamic bindings, etc.
return !node.if && !node.for && !node.hasBindings /* ... */;
}
The optimizer also marks static roots (staticRoot): static nodes with children, excluding those whose only child is a single text node.
How These Markers Help
These markers support later patching:
- Skip static subtrees: during a re-render, patch can recognize matching static nodes and skip detailed comparison of their subtrees.
- Cache and reuse static nodes: render static content once, then reuse the cached result instead of recreating it.
The optimizer does work at compile time, recording which parts never change so runtime diffing has less to do. This complements the node-by-node comparisons in the Snabbdom course: Vue uses compiler information to prune work before comparing nodes at runtime.
🛠 generate: AST → Render Code
The code generator in src/compiler/codegen/index.js converts the AST into a code string. Consider the same example:
<div id="app">
<p>{{ message }}</p>
hello
</div>
The generated code looks roughly like this:
with (this) {
return _c('div', { attrs: { id: 'app' } }, [_c('p', [_v(_s(message))]), _v('hello')]);
}
Wrapping that string with new Function produces an executable render function. Executing it returns a virtual node tree (vnode), which patch turns into real DOM.
Common Render Helpers
The names _c, _v, and _s are shorthand for helpers available on the component instance:
| Shorthand | Function | Purpose |
|---|---|---|
_c | createElement | Create an element vnode, similar to Snabbdom's h() |
_v | createTextVNode | Create a text vnode |
_s | toString | Convert a value to text ({{ message }} compiles to _s(message)) |
_l | renderList | Render a list; v-for compiles into an _l call |
For example, consider a v-for template:
<ul>
<li v-for="item in list">{{ item.name }}</li>
</ul>
It compiles roughly to:
with (this) {
return _c('ul', _l(list, function (item) {
return _c('li', [_v(_s(item.name))]);
}));
}
_l(list, fn) iterates over list, invokes the callback for each item to create a vnode, and collects the results as the ul children. These calls resemble the h('li', ...) calls we wrote in the Snabbdom course. The final output of template compilation describes virtual DOM in code.
💡 What with(this) Does
The generated render code is wrapped in with (this). This makes the component instance part of the scope used to resolve identifiers.
As a result, message resolves to the instance property, effectively this.message. This is why templates can use {{ message }} without writing {{ this.message }}.
with in strict mode ('use strict'), which is one reason Vue 2's generated render functions do not use strict mode. Vue 3 compilation uses different strategies depending on the build and compilation mode.with has costs: it complicates variable lookup and makes identifier origins less explicit. Templates typically access relatively few variables, limiting the practical impact in this context.
⚖️ Full Build vs. Runtime-Only Build
Does Vue compile templates every time the application runs? That depends on the build you use.
When installing Vue with npm (local environment: Node.js v22, vue@2.7.16):
# Node.js v22
npm install vue@2.7.16
The default builds (vue.runtime.common.js, or vue.runtime.esm.js resolved by bundlers) are runtime-only and exclude the template compiler. They expect templates to have been compiled into render functions during the build by vue-loader for .vue files or by vue-template-compiler. The runtime only renders, keeping the bundle smaller.
To compile the template option or the mount element's HTML in the browser, explicitly load the full build (vue/dist/vue.js, runtime plus compiler):
// Requires the full build: compile template at runtime
new Vue({
el: '#app',
template: '<div>{{ message }}</div>',
data: { message: 'hello' },
});
<template> in a .vue file does not require managing a browser compiler: compilation already happens during the build.The compiler and runtime are separate. The full build includes both and can compile templates at runtime; the runtime-only build requires templates to be compiled during the build.
❓ Knowledge Check
Q1: Are an AST and virtual DOM (vnode) the same thing?
No. An AST is an intermediate compile-time representation of template structure and expressions. VNodes are runtime objects produced by executing the render function. The sequence is template → AST → render function → vnode → real DOM.
Q2: Do static markers keep nodes out of the VNode tree?
No. Static nodes still produce VNodes and render normally. Their markers allow patch to skip detailed subtree comparisons and reuse cached output. This optimization does not change the rendered result.
Q3: Why does {{ message }} compile to _s(message) rather than using message directly?
Interpolation needs text. _s (toString) converts values such as numbers and objects into strings, avoiding results such as [object Object] from naive object concatenation.
Q4: Does using template with a runtime-only build immediately throw an error?
In development, if no render function is available, the runtime-only build warns that templates require the full build or a render function. Projects using normal build tooling avoid this because templates are precompiled.
Q5: When does template compilation happen?
It depends on the build. The full build can compile in the browser when mounting a new Vue instance. In a runtime-only project, tools such as vue-loader compile during the build, so the browser receives render functions.
🧪 Exercise
Without consulting the explanation above, write the render code for this template using _c, _l, _v, and _s:
<div>
<h1>{{ title }}</h1>
<ul>
<li v-for="todo in todos">{{ todo.text }}</li>
</ul>
</div>
with (this) {
// Write your code here
}
Check your answer: the h1 interpolation uses _v(_s(title)); the second argument to the ul call is _l(todos, function (todo) { ... }); and the callback returns _c('li', [_v(_s(todo.text))]).
🎉 You now understand the complete compilation pipeline! Vue transforms a template string into an AST and then into a render function through these three stages.
