I haven't found any mentions in the HTML spec nor anywhere on the web, that says this is possible, still I ask just in case.
Is it possible to get the URL of a module to for example fetch files relative to that URL?
Let's say my index.html
has a:
<script type="module">import '/foo/foo.js'</script>
and foo.js
wants to know what it's own url is to load dynamically some file e.g. ./file-inside-foo
.
As of the time of this writing document.currentScript
returns null
inside modules and is probably like that by design?
ECMA-262 has a Stage 3 Proposal for implementing import.meta
. On the web this exposes a property named url
that, when accessed from within a module, gives access to the full URL of that module.
// in /path/to/your/module.js
const { pathname } = new URL(import.meta.url);
console.log(pathname); // '/path/to/your/module.js'
You can also use the second parameter of the URL
constructor to skip a step here:
const url = new URL('relative/file.js', import.meta.url);
Unfortunately, import.meta
may not be available in all browsers yet but was implemented in v64 of Google Chrome.
The HTML Living Standard currently includes a Stage 3 Proposal to the ECMA-262 Standard that implements import.meta
which exposes a property named url
providing the full path to the current module including the protocol and filename.
// import.meta.url == 'http://your.domain.name/path/to/your/module.js'
To get the path of the current module without the protocol + domain you can construct a URL object from this value and access its .pathname
property:
const modulePath = new URL(import.meta.url).pathname;
// modulePath = '/path/to/your/module.js'
To determine the directory where the current module is located you would construct a URL object for the relative path ./
using import.meta.url
as the base
parameter:
const moduleDir = new URL('./', import.meta.url).pathname;
// moduleDir == '/path/to/your/'
You can also get the path of any file relative to the current module in the same manner. For example:
let img = new Image();
image.src = new URL('../icons/glyph.png', import.meta.url).pathname;
// image.src == '/path/to/icons/glyph.png'
Unfortunately import.meta may not be available in all browsers yet however it was implemented in v64 of Google Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With