获取当前模块脚本的URL

问题描述 投票:0回答:2

我在 HTML 规范 或网络上的任何地方都没有找到任何提及,这表明这是可能的,但为了以防万一,我还是问一下。

是否可以获取模块的 URL,例如获取与该 URL 相关的文件?

假设我的

index.html
有一个:

<script type="module">import '/foo/foo.js'</script>

foo.js
想知道它自己的url是什么来动态加载一些文件,例如
./file-inside-foo

截至撰写本文时,

document.currentScript
在模块内返回
null
,并且设计可能就是这样?

javascript html ecmascript-6
2个回答
10
投票

您可以使用

import.meta
。在网络上,这公开了一个名为
url
的属性,当从模块内访问时,可以访问该模块的完整 URL。

// in /path/to/your/module.js

const { pathname } = new URL(import.meta.url);
console.log(pathname); // '/path/to/your/module.js'

您还可以使用

URL
构造函数的第二个参数来跳过此处的步骤:

const url = new URL('relative/file.js', import.meta.url);

5
投票

您可以使用

import.meta
公开一个名为
url
的属性,提供当前模块的完整路径,包括协议和文件名。

// import.meta.url == 'http://your.domain.name/path/to/your/module.js'

要获取不带协议+域的当前模块的路径,您可以从此值构造一个 URL 对象并访问其

.pathname
属性:

const modulePath = new URL(import.meta.url).pathname;
// modulePath = '/path/to/your/module.js'

要确定当前模块所在的目录,您可以使用

./
作为
import.meta.url
参数来构造相对路径
base
的 URL 对象:

const moduleDir = new URL('./', import.meta.url).pathname;
// moduleDir == '/path/to/your/'

也可以用同样的方式获取任意文件相对于当前模块的路径。例如:

let img = new Image();
image.src = new URL('../icons/glyph.png', import.meta.url).pathname;
// image.src == '/path/to/icons/glyph.png'
© www.soinside.com 2019 - 2024. All rights reserved.