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
A relative URL can be conveniently converted into absolute by calling URL(relativeUrl, baseUrl)
constructor with import.meta.url
as the base URL:
console.log(new URL('./template.html', import.meta.url).href);
// http://192.168.0.24:5501/js/main/template.html
fetch()
accepts URL objects, so there is no real need to extract href
property from an URL object when calling fetch()
.
import.meta.resolve() — a modern alternative for URL with import.meta.url
Since Chrome 105, a simpler way to convert a URL relative to a module into an absolute URL is possible — instead of new URL('./template.html', import.meta.url)
one can use import.meta.resolve('./template.html')
. The result is the same:
console.log(import.meta.resolve('./template.html'));
// http://192.168.0.24:5501/js/main/template.html