Problem: I use Parcel as a bundler of my project and try to inject HTML markup into my index.html from my TypeScript file. Injected markup contains <img>
elements with dynamically resolved paths for their src
attribute. The paths I’m trying to add to the images’ src
attributes are stored as properties of my data.json file, which I import directly into my TypeScript file. The problem is that Parcel support only string literals inside new URL()
syntax, therefore I don’t know how to use template literals/variables inside this function to add dynamic URL dependencies.
Code:
import data from "../data.json";
const productList: HTMLUListElement | null = document.querySelector(
".product-list__list",
);
if (productList) {
for (const product of data) {
const markup = `
<img
src="${new URL(product.image.mobile, import.meta.url).toString()}"
alt="${product.name}"
class="product__image"
/>
`;
productList.insertAdjacentHTML("beforeend", markup);
}
}
What I’ve tried: I tried using template literals, variables inside new URL()
function, but it was in vain, since Parcel doesn’t support anything else than string literals inside of it.