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

问题描述 投票:1回答:1

我正在尝试使用<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: " + "???");

我在某个地方看到了一些讨论,当使用document.currentScriptnulltype="module"的原因是因为他们想要找出更好的选择。我想这个替代方案还没有?

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

javascript es6-modules
1个回答
0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.