# whatwg-url 中文文档

规范地址：https://npmcn.com/package/whatwg-url/

版本：17\.3\.0
npm 元数据更新时间：2026-10-14T03:17:27.143Z
中文译文更新时间：2026-11-04T13:03:43.016Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/whatwg-url
原文对照：https://npmcn.com/package/whatwg-url/?lang=original
项目主页：https://github.com/jsdom/whatwg-url#readme
源码仓库：https://github.com/jsdom/whatwg-url

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：120 kB，19 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：^22\.14\.0 \|\| \>=24\.0\.0
- 运行依赖：3 个
- 首次发布：2015-06-04T13:09:58.924Z
- 最新版本发布：2026-10-14T03:17:26.751Z
- 近 30 天下载量：1010789409（2026-10-06 至 2026-11-04，npm 官方下载统计）
- 已发布版本数：77（近 12 个月 8 个）

## 中文简介

WHATWG URL标准的URL API和解析机制的实现

## 安装

```sh
npm install whatwg-url
```

也可以使用：`pnpm add whatwg-url`、`yarn add whatwg-url`、`bun add whatwg-url`

## README

# whatwg-url

WHATWG -url是WHATWG的完整实现 [URL标准](https://url.spec.whatwg.org/)． 它可以独立使用，但它也暴露了许多内部算法，这些算法对于将URL解析器集成到项目中很有用 [jsdom](https://github.com/jsdom/jsdom)。

## 规范的一致性

whatwg-url目前是最新的，URL规范即将提交 [fde3f74](https://github.com/whatwg/url/commit/fde3f74f063341a28d437216f75735b8b40128f5)。

为 `file:` url,其 [原点未指定](https://url.spec.whatwg.org/#concept-url-origin)， whatwg-url选择使用一个新的不透明源(序列化为 `"null"`）.

## API

### 这个 `URL` 和 `URLSearchParams` 类

类提供了主API [`URL`](https://url.spec.whatwg.org/#url-class) 和 [`URLSearchParams`](https://url.spec.whatwg.org/#interface-urlsearchparams) 导出，它在所有方面都遵循规范的行为(包括例如： `USVString` 转换)。此库的大多数用户都希望使用这些。

### 低级URL标准API

下面的方法被导出，供jdom等需要实现以下功能的地方使用 [`HTMLHyperlinkElementUtils`](https://html.spec.whatwg.org/#htmlhyperlinkelementutils)． 它们主要操作或返回“内部URL”或 [“网址记录”](https://url.spec.whatwg.org/#concept-url) 类型。

-   [URL解析器](https://url.spec.whatwg.org/#concept-url-parser)： `parseURL(input, { baseURL, encoding = "UTF-8" })`
-   URL解析器 [验证错误](https://url.spec.whatwg.org/#validation-error)： `parseURLWithValidationErrors(input, { baseURL, encoding = "UTF-8" })`
-   [有效的URL字符串](https://url.spec.whatwg.org/#valid-url-string) 检查程序: `isValidURLString(input, { baseURL })`
-   [基本URL解析器](https://url.spec.whatwg.org/#concept-basic-url-parser)： `basicURLParse(input, { baseURL, url, stateOverride, encoding = "UTF-8" })`
-   [URL序列化器](https://url.spec.whatwg.org/#concept-url-serializer)： `serializeURL(urlRecord, excludeFragment)`
-   [主机序列化器](https://url.spec.whatwg.org/#concept-host-serializer)： `serializeHost(hostFromURLRecord)`
-   [URL路径序列化器](https://url.spec.whatwg.org/#url-path-serializer)： `serializePath(urlRecord)`
-   [序列化一个整数](https://url.spec.whatwg.org/#serialize-an-integer)： `serializeInteger(number)`
-   [起源](https://url.spec.whatwg.org/#concept-url-origin) [序列化器](https://html.spec.whatwg.org/multipage/origin.html#ascii-serialisation-of-an-origin)： `serializeURLOrigin(urlRecord)`
-   [设置用户名](https://url.spec.whatwg.org/#set-the-username)： `setTheUsername(urlRecord, usernameString)`
-   [设置密码](https://url.spec.whatwg.org/#set-the-password)： `setThePassword(urlRecord, passwordString)`
-   [有不透明的路径](https://url.spec.whatwg.org/#url-opaque-path)： `hasAnOpaquePath(urlRecord)`
-   [不能有用户名/密码/端口](https://url.spec.whatwg.org/#cannot-have-a-username-password-port)： `cannotHaveAUsernamePasswordPort(urlRecord)`
-   [解码字节百分比](https://url.spec.whatwg.org/#percent-decode)： `percentDecodeBytes(uint8Array)`
-   [%解码字符串](https://url.spec.whatwg.org/#string-percent-decode)： `percentDecodeString(string)`

这个 `stateOverride` 参数为以下字符串之一：

-   [`"scheme start"`](https://url.spec.whatwg.org/#scheme-start-state)
-   [`"scheme"`](https://url.spec.whatwg.org/#scheme-state)
-   [`"no scheme"`](https://url.spec.whatwg.org/#no-scheme-state)
-   [`"special relative or authority"`](https://url.spec.whatwg.org/#special-relative-or-authority-state)
-   [`"path or authority"`](https://url.spec.whatwg.org/#path-or-authority-state)
-   [`"relative"`](https://url.spec.whatwg.org/#relative-state)
-   [`"relative slash"`](https://url.spec.whatwg.org/#relative-slash-state)
-   [`"special authority slashes"`](https://url.spec.whatwg.org/#special-authority-slashes-state)
-   [`"special authority ignore slashes"`](https://url.spec.whatwg.org/#special-authority-ignore-slashes-state)
-   [`"authority"`](https://url.spec.whatwg.org/#authority-state)
-   [`"host"`](https://url.spec.whatwg.org/#host-state)
-   [`"hostname"`](https://url.spec.whatwg.org/#hostname-state)
-   [`"port"`](https://url.spec.whatwg.org/#port-state)
-   [`"file"`](https://url.spec.whatwg.org/#file-state)
-   [`"file slash"`](https://url.spec.whatwg.org/#file-slash-state)
-   [`"file host"`](https://url.spec.whatwg.org/#file-host-state)
-   [`"path start"`](https://url.spec.whatwg.org/#path-start-state)
-   [`"path"`](https://url.spec.whatwg.org/#path-state)
-   [`"opaque path"`](https://url.spec.whatwg.org/#cannot-be-a-base-url-path-state)
-   [`"query"`](https://url.spec.whatwg.org/#query-state)
-   [`"fragment"`](https://url.spec.whatwg.org/#fragment-state)

URL记录类型有以下API：

-   [`scheme`](https://url.spec.whatwg.org/#concept-url-scheme)
-   [`username`](https://url.spec.whatwg.org/#concept-url-username)
-   [`password`](https://url.spec.whatwg.org/#concept-url-password)
-   [`host`](https://url.spec.whatwg.org/#concept-url-host)
-   [`port`](https://url.spec.whatwg.org/#concept-url-port)
-   [`path`](https://url.spec.whatwg.org/#concept-url-path) （作为字符串数组或字符串）
-   [`query`](https://url.spec.whatwg.org/#concept-url-query)
-   [`fragment`](https://url.spec.whatwg.org/#concept-url-fragment)

应该小心处理这些属性，因为更改它们通常会导致URL记录处于不一致的状态，直到适当调用 `basicURLParse` 是用来修理的。您可以在URL标准中看到这样的示例，其中有许多步骤序列，如“4”。将上下文对象的url片段设置为空字符串。5. 基本URL解析 _输入_ 使用上下文对象的url作为 _url_ 片段状态为 _状态覆盖_．" 在这两个步骤之间，URL记录处于不可用状态。

规范中“failure”的返回值表示为 `null`． 也就是像这样的函数 `parseURL` 和 `basicURLParse` 可以返回 _要么_ URL记录 _或_ `null`。

这个 `parseURLWithValidationErrors` 函数返回一个带有 `url` 属性和a `validationErrors` 财产。这个 `url` 属性是URL记录或 `null`，和 `validationErrors` 属性是解析时报告的验证错误名称的数组。

```js
const result = parseURLWithValidationErrors("https://example.org/%s");

console.log(result.url === null); // false
console.log(result.validationErrors); // [ "invalid-URL-unit" ]
```

这个 `isValidURLString` 函数从URL标准的URL编写部分实现基于语法的有效性检查器。这与解析器验证错误是分开的，所以它可以不同意 `parseURLWithValidationErrors()` 在某些情况下。通过一项 `baseURL` URL记录，用于检查相对URL字符串。

### `whatwg-url/webidl2js-wrapper` 模块

该模块导出 `URL` 和 `URLSearchParams` [接口包装API](https://github.com/jsdom/webidl2js#for-interfaces) 生成的 [webidl2js](https://github.com/jsdom/webidl2js)。

## 开发说明

首先,安装 [node . js](https://nodejs.org/)． 然后，从这个目录下运行，获取whatwg-url的依赖项：

```
npm install
```

要运行测试：

```
npm test
```

要生成覆盖率报告：

```
npm run coverage
```

要构建和运行实时查看器：

```
npm run prepare
npm run build-live-viewer
```

服务的内容 `live-viewer` 目录使用任何web服务器。

## 支持whatwg-url

jdom项目（包括whatwg-url）是一个社区驱动的项目，由一个团队维护 [志愿者](https://github.com/orgs/jsdom/people)． 您可以通过以下方式支持我们：

-   [获得whatwg-url的专业支持](https://tidelift.com/subscription/pkg/npm-whatwg-url?utm_source=npm-whatwg-url&utm_medium=referral&utm_campaign=readme) 作为Tidelift订阅的一部分。Tidelift帮助我们实现开源的可持续性，同时为团队提供维护、许可和安全性方面的保证。
-   直接对项目做出贡献。

## 常见问题

### whatwg-url 是什么？

WHATWG URL标准的URL API和解析机制的实现

### 如何安装 whatwg-url？

在项目目录运行 npm install whatwg-url，或使用 pnpm add / yarn add / bun add。

### whatwg-url 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/whatwg-url 是否存在。

### whatwg-url 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### whatwg-url 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js ^22\.14\.0 \|\| \>=24\.0\.0。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### whatwg-url 可以商用吗？

whatwg-url 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### whatwg-url 的下载量有多少？

根据 npm 官方下载统计，whatwg-url 在 2026/10/06 – 2026/11/04 这 30 天内被下载 1,010,789,409 次，日均约 33,692,980 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### whatwg-url 还在维护吗？

最新版本 17\.3\.0 发布于 2026/10/14（23 天前）；至今共发布 77 个版本，其中过去 12 个月发布了 8 个；首次发布于 2015/06/04。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

