结论
虽然不严格限制在使用 mini_racer 时,但请注意 Node.js API URL 有 legacy API 和 WHATWG compliant API
(浏览器的 URL API 也符合 WHATWG API)
引用上面的 API 文档:
下图显示了使用两种 API 解析 URL 'https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash' 时的差异。
上半部分是使用旧版 API 的url.parse() 时,下半部分代表 WHATWG URL 对象的属性。
有许多不同之处,例如 origin 属性。
┌────────────────────────────────────────────────────────────────────────────────────────────────┐
│ href │
├──────────┬──┬─────────────────────┬────────────────────────┬───────────────────────────┬───────┤
│ protocol │ │ auth │ host │ path │ hash │
│ │ │ ├─────────────────┬──────┼──────────┬────────────────┤ │
│ │ │ │ hostname │ port │ pathname │ search │ │
│ │ │ │ │ │ ├─┬──────────────┤ │
│ │ │ │ │ │ │ │ query │ │
" https: // user : pass @ sub.example.com : 8080 /p/a/t/h ? query=string #hash "
│ │ │ │ │ hostname │ port │ │ │ │
│ │ │ │ ├─────────────────┴──────┤ │ │ │
│ protocol │ │ username │ password │ host │ │ │ │
├──────────┴──┼──────────┴──────────┼────────────────────────┤ │ │ │
│ origin │ │ origin │ pathname │ search │ hash │
├─────────────┴─────────────────────┴────────────────────────┴──────────┴────────────────┴───────┤
│ href │
└────────────────────────────────────────────────────────────────────────────────────────────────┘
此外,旧 API 中的解析方法不同,url.parse() 是在导入模块后完成的。
// WHATWG API
const myURL = new URL('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
// legacy API
import url from 'node:url';
const myURL = url.parse('https://user:pass@sub.example.com:8080/p/a/t/h?query=string#hash');
卡点
我尝试在使用 mini_racer 作为 JavaScript 运行时的环境中使用 URL API。
mini_racer 使用 V8 作为其 JavaScript 引擎,但与浏览器和 Node.js 不同,它没有实现 URL API。
所以起初我试图使用下面的node-url 包。
在 webpack 4 之前,这个包是作为后备自动添加的。
然而,这个包为 Node.js 提供了一个 URL 模块(遗留 API),它不能像new URL() 那样使用,就像一个 WHATWG 兼容的 API。
我不知道有两种类型的 Node.js URL API...
如何回应
我使用了whatwg-url 并使用了符合 WHATWG 的 URL API 以及浏览器。
import { URL, URLSearchParams } from 'whatwg-url'
const url = new URL('https://qiita.com')
const params = new URLSearchParams('?param=value')
剩余的挑战
例如,如果你想在浏览器上运行一个 SSR 组件,你可以用上面的方法来做,但是由于浏览器实现了 URL API,你会导入不必要的源代码。
因此,如下图,我想包含一个流程,判断是否在 globalThis 中实现了 URL API,并确定要使用的 API。
import {
URL as whatwgURL,
URLSearchParams as whatwgURLSearchParams,
} from 'whatwg-url'
let hasNative
let outputURL
let outputURLSearchParams
try {
const url = new globalThis.URL('https://qiita.com')
const params = new globalThis.URLSearchParams('?param=value')
hasNative = 'searchParams' in url && params.get('param') === 'value'
} catch (error) {
hasNative = false
}
if (hasNative) {
outputURL = globalThis.URL
outputURLSearchParams = globalThis.URLSearchParams
} else {
outputURL = whatwgURL
outputURLSearchParams = whatwgURLSearchParams
}
export { outputURL as URL, outputURLSearchParams as URLSearchParams }
原创声明:本文系作者授权爱码网发表,未经许可,不得转载;
原文地址:https://www.likecs.com/show-308632950.html