Member-only story
import.meta.resolve() — a novel fancy feature of JavaScript modules
Using import maps for loading HTML templates into JavaScript modules
JavaScript modules can import JSONs
import data from '/api/data.json' assert { type: "json" };
but do not yet support import
s of HTML templates. To load a template into a module one needs to use a longer code with fetch()
and await
.
const html = await fetch(new URL('./template.html',import.meta.url)) .then(res => res.text());
Normally, a template and the module loading it are saved in the same folder. So inside the module, the template can be referred to using short relative URL such as ./template.html. However, such a relative URL cannot be directly passed to fetch()
because fetch()
resolves relative URLs relative to the page base URL. In the module, it is possible to convert the path to the template into a URL relative to the page base URL, but it is easier to convert it into an absolute URL.
Creating URL object
Considering that import.meta.url
holds the absolute URL of the currently executing module:
console.log(import.meta.url);
// http://192.168.0.24:5501/js/main/main.js