16

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?

1

2 Answers 2

11

You 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);
Sign up to request clarification or add additional context in comments.

Comments

7

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'

4 Comments

please use new URL(import.meta.url) to parse a URL, not manually splitting.
const { modulePath } = new URL('./', import.meta.url).pathname; should be const modulePath = new URL('./', import.meta.url).pathname; or const { pathname: modulePath } = new URL('./', import.meta.url);
I feel I should point out that @snek is a contributor to these proposed standards and part of the reason these great new features exist. His contributions to both the web and this answer should be noted.
thanks :) But I haven't put any work into the import.meta proposal or URL standard. There are other people who should get credit long before I do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.