繁体   English   中英

type =“module”的当前脚本路径

[英]Current script path with type=“module”

我正在尝试使用<script type="module">访问我想要相对于脚本文件引用的文件。 通常,如果没有type =“module”,人们似乎正在查找脚本标记并使用其src属性来获取路径,但这在使用导入后显然是不可能的。

该场景看起来大致如下:

文件结构:

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: " + "???");

我在某处讨论过使用type="module"document.currentScriptnull的原因是因为他们想找出更好的选择。 我想这个替代方案还没有?

那么,回顾一下,使用上面的文件结构,如何动态地找到该脚本中js / other / imported.js的路径?

为了在将近2年后回答我自己的问题,现在有一个名为import.meta的东西,它用于提供有关当前模块的任意信息。 在这种情况下, import.meta.url将是我想要的东西。

您可以在此MDN页面上阅读更多内容: https//developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import.meta

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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