简体   繁体   中英

Current script path with type=“module”

I'm trying to access a file that I want to reference relative to a script file while using <script type="module"> . Normally, without type="module", people seem to be looking up the script tag and using its src attribute to get the path, but this obviously isn't possible after using imports.

The scenario looks roughly like this:

File structure:

js/
    script.js
    other/
        imported.js
index.html

index.html:

<html><head><script type="module" src="js/script.js"></script></head></html>

script.js

import "other/imported.js";

imported.js

// ??? should with some code magic become "js/other/imported.js" or similar
console.log("The path to this script is: " + "???");

I saw some thread somewhere where it was discussed that the reason document.currentScript is null when using type="module" is because they wanted to figure out a better alternative. I suppose this alternative is not yet available?

So, to recap, with the file structure above, how can one find the path to js/other/imported.js in that script dynamically?

To answer my own question almost 2 years later, there's now a thing called import.meta which is used to provide arbitrary information about the current module. In this case, import.meta.url would be the thing I was looking for.

You can read more on this MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM