How to import HTML template file into JavaScript module
--
import template from './temlplate.html';
does not work in a browser.
Although some frameworks oblige developers to mix everything, generally web development is easier when the layout, styles and application logic are separated. You layout a page and its component in .html files, style them in .css files and add the logic implemented in many tiny modules each dedicated to a discrete task. If clients ask to change some color, you change it in CSS without touch the rest of the code. If you have to change some title or add a container for a new component, you just adjust an .html file.
RequireJS, a lovely library implementing Asynchronous Module Definition (AMD) API, for years have enabled developers to divide applications into many components that are executable directly in the browser. Development and debugging is much faster when changes to the code are seen in the browser immediately, without any annoying delay for transpilation, compilation or bundling. Bundling might be necessary for production but during development it is a waste of time in the name of a framework. Now that the native JavaScript modules (also called ES modules or ES6 modules) started to catch up with RequireJS, there is no absolute need to bundle even for production, particularly in enterprise web applications.
Every component visible on a web page is visible because it has HTML. Let’s consider how to import an HTML template into a module implementing the logic of a component shown as a tab on an imaginary web page. With RequireJS it is straightforward:
define(["text!./template.html"],
function(template) {
leftTab.innerHTML = template;
// attach listeners, load and render data, ...
});
leftTab
is the id
of the div
that serves as the placeholder for the component’s HTML. It is a matter of taste, but sometimes the code is more legible without dispensable methods like getElementById()
. The module above displays a component using one line — leftTab.innerHTML = template;
. Some people prefer using obsolete appendChild()
or more modern methods. But it is smarter to use innerHTML
for inserting HTML templates because:
- the code is shorter
- you can easy manipulate the HTML template and see how it…