VueJS and HTML Imports

Introducing the situation

I really like VueJS since it combines all the best of Angular, React and Polymer. It makes writing components easy and uses expressions like Angular in its template syntax. You can even render your components using JSX..

One thing I missed was using single file components with separate templates and scripts, you know, the way Polymer does allow us to create components. Here is an example of a polymer component:

polymer

Note how the template and the element registration are separated, giving us single file but still separation of code and markup.

The problem

In VueJS, without using a serverside technique, the only options to write your code is to use templates as inline strings or use the hack shown below:

Vue1

While this is giving us the benefits of separating the code and the markup, this does not work if we were to create separate files for each component we want to write. Including this into a .JS file would not work, since the contents of the script tag with the markup is script.

Sure we could separate the script that registers the component into its own file, but then we would have the markup and the code shattered in more files.. yuck!

HTML Imports

Polymer makes use of HTML Imports. If you want to know more about this spec, read more about it here.

So HTML Imports give us the benefits of loading (async if preferred) HTML assets, which can contain HTML markup and scripts.. My idea was to make use of HTML Imports when writing VueJS components so I can author VueJS Components each into its own file while still separating the markup and code.

In the code below, I’ve created a name-badge.html file with the following contents:

Vue2

Then in the index.html page, I just refer to this file using the html import tag like this:

Vue3

This setup works similar to Polymers setup and works fine by me. Of course, when building more complex and larger applications using VueJS, you really should use a more professional setup.

For more information about .vue files in a serverside setup, I would recommend reading this guide from VueJS.

 

Leave a comment