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.
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:
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…