> ## Documentation Index
> Fetch the complete documentation index at: https://bun.zhcndoc.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 语义化版本

> 使用 Bun 的语义化版本 API

Bun 实现了一个语义化版本（semver）的 API，可用于比较版本并判断某个版本是否兼容另一版本范围。这些版本和范围设计上兼容 `node-semver`，后者被 npm 客户端广泛使用。

它的速度大约是 `node-semver` 的 20 倍。

<Frame>![性能基准](https://github.com/oven-sh/bun/assets/709451/94746adc-8aba-4baf-a143-3c355f8e0f78)</Frame>

目前，该 API 提供了两个函数：

## `Bun.semver.satisfies(version: string, range: string): boolean`

如果 `version` 满足 `range`，则返回 `true`，否则返回 `false`。

示例：

```typescript theme={"theme":{"light":"github-light","dark":"dracula"}}
import { semver } from "bun";

semver.satisfies("1.0.0", "^1.0.0"); // true
semver.satisfies("1.0.0", "^1.0.1"); // false
semver.satisfies("1.0.0", "~1.0.0"); // true
semver.satisfies("1.0.0", "~1.0.1"); // false
semver.satisfies("1.0.0", "1.0.0"); // true
semver.satisfies("1.0.0", "1.0.1"); // false
semver.satisfies("1.0.1", "1.0.0"); // false
semver.satisfies("1.0.0", "1.0.x"); // true
semver.satisfies("1.0.0", "1.x.x"); // true
semver.satisfies("1.0.0", "x.x.x"); // true
semver.satisfies("1.0.0", "1.0.0 - 2.0.0"); // true
semver.satisfies("1.0.0", "1.0.0 - 1.0.1"); // true
```

如果 `range` 无效，则返回 false。如果 `version` 无效，也返回 false。

## `Bun.semver.order(versionA: string, versionB: string): 0 | 1 | -1`

当 `versionA` 和 `versionB` 相等时返回 `0`，当 `versionA` 大于 `versionB` 时返回 `1`，当 `versionA` 小于 `versionB` 时返回 `-1`。

示例：

```typescript theme={"theme":{"light":"github-light","dark":"dracula"}}
import { semver } from "bun";

semver.order("1.0.0", "1.0.0"); // 0
semver.order("1.0.0", "1.0.1"); // -1
semver.order("1.0.1", "1.0.0"); // 1

const unsorted = ["1.0.0", "1.0.1", "1.0.0-alpha", "1.0.0-beta", "1.0.0-rc"];
unsorted.sort(semver.order); // ["1.0.0-alpha", "1.0.0-beta", "1.0.0-rc", "1.0.0", "1.0.1"]
console.log(unsorted);
```

如果你需要其它语义化版本相关的函数，欢迎提出 issue 或提交 pull request。
