简体   繁体   English

从 ES6 模块解析到绝对 url 的相对路径(在浏览器中)

[英]Resolve relative path to absolute url from ES6 module (in browser)

How to resolve relative path to absolute url in ES6 module (in browser)?如何在 ES6 模块(在浏览器中)中解析到绝对 url 的相对路径?

For example:例如:

base-url.com/
    |-resolve
    |   |-resolveUrl.js
    |-dir
        |-dir1
            |-module1.js
        |-dir2
            |-module2.js

module1.js模块1.js

import resolveUrl from "../../../resolve/resolveUrl.js"
resolveUrl("../dir2/module2.js") // return 'base-url.com/dir/dir2/module2.js'

What would be the resolveUrl implementation? resolveUrl的实现是什么?

base-url.com/ may not be the web-site's domain. base-url.com/可能不是该网站的域。 It can be a repo where only sources are stored.它可以是只存储源的回购协议。

🎉 You can now use to-absolute-url . 🎉 您现在可以使用to-absolute-url

It uses stacktrace.js under the hoods to get the caller function's absolute path file:它在底层使用stacktrace.js来获取调用者函数的绝对路径文件:

Thanks to @PatrickRoberts for his idea to use stacktrace, and @jfriend00 for his tip to use URL object.感谢@PatrickRoberts提出使用堆栈跟踪的想法,感谢@jfriend00提供使用URL对象的提示。

How about怎么样

const a = document.createElement('a')

function resolveUrl(path) {
  a.href = path
  return a.href // magic happens
}

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

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