import.meta object. It exposes information about the current module, such as its URL.
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.
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
app.js via a
<script type="module"> tag...
...If you run this code using the Live Server extension for VS code, the image URL is the absolute URL
http://127.0.0.1:5500/cat.jpeg. It's not just the relative URL
cat.jpeg; the base URL is
http://127.0.0.1:5500, which is the
import.meta.url in this case.