A few weeks ago, I discovered a feature of JavaScript modules that I never knew about: the import.meta object. It exposes information about the current module, such as its URL.

The import.meta.url property

At the time of writing, the import.meta object only has one property available to it: url. This property is a string representing the base URL of the module.

According to the MDN Web Docs:

This will either be the URL from which the script was obtained, for external scripts, or the document base URL of the containing document, for inline scripts.

Referencing an image relative to a module

The Parcel.js documentation offers a handy use case for the import.meta.url property: referencing an image relative to a module. You can do this by combining it with the URL() constructor we looked at last week:

const img = new Image();

const src = new URL("cat.jpeg", import.meta.url);
const alt = "A grey cat with bright blue eyes looks up at the camera.";

img.src = src;
img.alt = alt;

By passing the import.meta.url property as the second argument to the URL() constructor, we're using it as the base URL for the image. This means that the path cat.jpeg will be resolved relative to the module.

Assume a flat file structure as follows, where index.html imports app.js via a <script type="module"> tag...

  • app.js
  • cat.jpeg
  • index.html

...If you run this code using the Live Server extension for VS code, the image URL is the absolute URL It's not just the relative URL cat.jpeg; the base URL is, which is the import.meta.url in this case.