Build a Vue template compiler: parse to an AST and generate a render function for v-if, v-for, :bind and @on
Problem
Vue compiles every template into a render function: plain JavaScript that returns virtual nodes. Knowing what that function looks like explains most of Vue's template rules: why v-if beats v-for, why whitespace between elements disappears, why @click="count++" works but @click="count" passes the event to a method. Build a small compiler for the core syntax.
const render = compile(`<ul>
<li v-for="(todo, i) in todos" :key="todo.id" @click="select(todo)">{{ i + 1 }}. {{ todo.title }}</li>
</ul>`);
render({ todos: [{ id: 7, title: "Buy milk" }], select });
// { type: "ul", key: null, props: null, children: [
// { type: "#fragment", ..., children: [{ type: "li", key: 7, props: { key: 7, onClick: fn }, children: "1. Buy milk" }] } ] }Ref. UR-1458 · © UIRound · uiround.com/questions/build-a-vue-template-compiler-parse-to-an-ast-and-generate-a-render-function-for-v-if-v-for-bind-and-on
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 5
- code listings
- 8
- edge cases
- 5
- follow-up questions
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1Parse with one recursive function over a cursor:
{{starts an interpolation,<!--a comment to skip,<plus a letter an element,</the end of the current element, anything else text up to the next of those. Keep a stack of open elements so an end tag can be checked against it.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.