An Introduction to Vue Template Compiler

May 31, 2019

The vue-template-compiler module is a powerful tool for compiling Vue templates and single file components into JavaScript. Most developers don't use vue-template-compiler directly. But bundler tools like vue-loader for Webpack use vue-template-compiler to do the heavy lifting of actually compiling .vue files.

The vue-template-compiler has two primary functions: converting templates to render() functions and parsing single file componens.

Compile Template to Render Function

A Vue template is just a plain string. Vue-template-compiler's compile() function converts a template string that you can use as a render() function for your components.

const compiler = require('vue-template-compiler');
const { renderToString } = require('vue-server-renderer').createRenderer();

// Compile a `render()` function based on a string template
const { render } = compiler.compileToFunctions('<h1>Hello, {{message}}</h1>');

Vue.component('hello', {
  props: ['message'],
  render
});

const app = new Vue({
  template: '<hello message="World"></hello>'
});

// <h1 data-server-rendered="true">Hello, World</h1>
const data = await renderToString(app);

Parsing a .vue File

Vue-template-compiler has a separate function called parseComponent() that helps you compile single file components (.vue files) into JavaScript.

const compiler = require('vue-template-compiler');
const parsed = compiler.parseComponent(`
  <template>
    <h1>{{message}}</h1>
  </template>
  <script>
    module.exports = {
      data: () => ({ message: 'Hello World' })
    };
  </script>
`);

// Contains `template`, `data` properties
const appComponent = Object.assign({ template: parsed.template.content },
  eval(parsed.script.content));
Vue.component('app', appComponent);
const app = new Vue({
  template: '<app></app>'
});

const data = await renderToString(app);
// <h1 data-server-rendered="true">Hello World</h1>
data;

More Vue Tutorials