Member-only story

import.meta.resolve() — a novel fancy feature of JavaScript modules

Using import maps for loading HTML templates into JavaScript modules

Marian C.
3 min readSep 15, 2022

JavaScript modules can import JSONs

import data from '/api/data.json' assert { type: "json" };

but do not yet support imports 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

--

--

Marian C.
Marian C.

Written by Marian C.

Java, JavaScript and SQL developer. Interested in data collection and visualization.

Responses (2)