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?
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?
- 6 ok, I found this github.com/whatwg/html/issues/1013 it seems it's still an open issue – olanod Commented Oct 11, 2017 at 15:13
2 Answers
Reset to default 11You can use 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);
You can use 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'