Build a Vue template compiler: parse to an AST and generate a render function for v-if, v-for, :bind and @on

hardAbout 70 minutesUpdated CodingProvuecompilerparsingastcode-generation
Not solved

Share this question

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

Stuck? Take a hint

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.

Every question and answer7 days, one payment