【问题标题】:Get URL of current module script获取当前模块脚本的 URL
【发布时间】:2018-03-23 08:04:16
【问题描述】:

我在HTML spec 和网络上的任何地方都没有发现任何提及,这表明这是可能的,但我还是问一下以防万一。

是否可以获取模块的 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


【解决方案1】:

ECMA-262 有一个 Stage 3 Proposal 用于实现 import.meta。在 Web 上,这会公开一个名为 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);

很遗憾,import.meta 可能尚未在所有浏览器中都可用,但 implemented in v64 of Google Chrome 是可用的。

【讨论】:

    【解决方案2】:

    HTML Living Standard 当前包含一个 Stage 3 ProposalECMA-262 Standard,它实现了 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'
    

    不幸的是 import.meta 可能尚未在所有浏览器中可用,但它是 implemented in v64 of Google Chrome

    【讨论】:

    • 请使用new URL(import.meta.url)解析网址,不要手动拆分。
    • const { modulePath } = new URL('./', import.meta.url).pathname; 应该是 const modulePath = new URL('./', import.meta.url).pathname;const { pathname: modulePath } = new URL('./', import.meta.url);
    • 我觉得我应该指出@snek 是这些提议标准的贡献者,也是这些伟大新功能存在的部分原因。应该注意他对网络和这个答案的贡献。
    • 谢谢 :) 但我没有在 import.meta 提案或 URL 标准中做任何工作。还有其他人应该比我早早获得荣誉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-27
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多