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

> 使用 Bun 的 JavaScript 和 TypeScript 压缩器减小包体积

# Minifier

Bun 包含一个快速的 JavaScript 和 TypeScript 压缩器，可以将包体积减少 80% 或更多（取决于代码库），并使输出代码运行更快。该压缩器执行数十种优化，包括常量折叠、死代码消除和语法转换。与其他压缩器不同，Bun 的压缩器使 `bun build` 运行更快，因为需要打印的代码更少。

## CLI 用法

### 启用所有压缩

使用 `--minify` 标志启用所有压缩模式：

```bash theme={null}
bun build ./index.ts --minify --outfile=out.js
```

`--minify` 标志启用：

* 空白压缩
* 语法压缩
* 标识符压缩

### 生产模式

`--production` 标志自动启用压缩：

```bash theme={null}
bun build ./index.ts --production --outfile=out.js
```

`--production` 标志同时：

* 将 `process.env.NODE_ENV` 设置为 `production`
* 启用生产模式的 JSX 导入和转换

### 精细控制

单独启用特定的压缩模式：

```bash theme={null}
# 仅移除空白
bun build ./index.ts --minify-whitespace --outfile=out.js

# 仅压缩语法
bun build ./index.ts --minify-syntax --outfile=out.js

# 仅压缩标识符
bun build ./index.ts --minify-identifiers --outfile=out.js

# 组合指定模式
bun build ./index.ts --minify-whitespace --minify-syntax --outfile=out.js
```

## JavaScript API

编程式使用 Bun 的打包器时，通过 `minify` 选项配置压缩：

```ts theme={null}
await Bun.build({
  entrypoints: ["./index.ts"],
  outdir: "./out",
  minify: true, // 启用所有压缩模式
});
```

要精细控制，传入一个对象：

```ts theme={null}
await Bun.build({
  entrypoints: ["./index.ts"],
  outdir: "./out",
  minify: {
    whitespace: true,
    syntax: true,
    identifiers: true,
  },
});
```

## 压缩模式

Bun 的压缩器有三个独立的模式，可以单独或一起启用。

### 空白压缩（`--minify-whitespace`）

移除输出中的所有不必要空白、换行和格式。

### 语法压缩（`--minify-syntax`）

将 JavaScript 语法重写为更短的等效形式，并执行常量折叠、死代码消除和其他优化。

### 标识符压缩（`--minify-identifiers`）

使用基于频率的优化将局部变量和函数名重命名为更短的标识符。

## 所有转换

### 布尔字面量缩短

**模式：** `--minify-syntax`

将布尔字面量转换为更短的表达式。

```ts 输入 theme={null}
true
false
```

```js 输出 theme={null}
!0
!1
```

### 布尔代数优化

**模式：** `--minify-syntax`

使用逻辑规则简化布尔表达式。

```ts 输入 theme={null}
!!x
x === true
x && true
x || false
!true
!false
```

```js 输出 theme={null}
x
x
x
x
!1
!0
```

### undefined 缩短

**模式：** `--minify-syntax`

将 `undefined` 替换为更短的等效形式。

```ts 输入 theme={null}
undefined
let x = undefined;
```

```js 输出 theme={null}
void 0
let x=void 0;
```

### undefined 相等优化

**模式：** `--minify-syntax`

优化与 undefined 的宽松相等检查。

```ts 输入 theme={null}
x == undefined
x != undefined
```

```js 输出 theme={null}
x == null
x != null
```

### Infinity 缩短

**模式：** `--minify-syntax`

将 Infinity 转换为数学表达式。

```ts 输入 theme={null}
Infinity
-Infinity
```

```js 输出 theme={null}
1/0
-1/0
```

### typeof 优化

**模式：** `--minify-syntax`

优化 typeof 比较并评估常量 typeof 表达式。

```ts 输入 theme={null}
typeof x === 'undefined'
typeof x !== 'undefined'
typeof require
typeof null
typeof true
typeof 123
typeof "str"
typeof 123n
```

```js 输出 theme={null}
typeof x>'u'
typeof x<'u'
"function"
"object"
"boolean"
"number"
"string"
"bigint"
```

### 数字格式化

**模式：** `--minify-syntax`

以最紧凑的表示形式格式化数字。

```ts 输入 theme={null}
10000
100000
1000000
1.0
-42.0
```

```js 输出 theme={null}
1e4
1e5
1e6
1
-42
```

### 算术常量折叠

**模式：** `--minify-syntax`

在编译时评估算术运算。

```ts 输入 theme={null}
1 + 2
10 - 5
3 * 4
10 / 2
10 % 3
2 ** 3
```

```js 输出 theme={null}
3
5
12
5
1
8
```

### 位运算常量折叠

**模式：** `--minify-syntax`

在编译时评估位运算。

```ts 输入 theme={null}
5 & 3
5 | 3
5 ^ 3
8 << 2
32 >> 2
~5
```

```js 输出 theme={null}
1
7
6
32
8
-6
```

### 字符串拼接

**模式：** `--minify-syntax`

在编译时合并字符串字面量。

```ts 输入 theme={null}
"a" + "b"
"x" + 123
"foo" + "bar" + "baz"
```

```js 输出 theme={null}
"ab"
"x123"
"foobarbaz"
```

### 字符串索引

**模式：** `--minify-syntax`

在编译时评估字符串字符访问。

```ts 输入 theme={null}
"foo"[2]
"hello"[0]
```

```js 输出 theme={null}
"o"
"h"
```

### 模板字面量折叠

**模式：** `--minify-syntax`

评估带有常量表达式的模板字面量。

```ts 输入 theme={null}
`a${123}b`
`result: ${5 + 10}`
```

```js 输出 theme={null}
"a123b"
"result: 15"
```

### 模板字面量转字符串

**模式：** `--minify-syntax`

将没有替换内容的模板字面量转换为常规字符串。

```ts 输入 theme={null}
`Hello World`
`Line 1
Line 2`
```

```js 输出 theme={null}
"Hello World"
"Line 1\nLine 2"
```

### 字符串引号优化

**模式：** `--minify-syntax`

选择最佳引号字符以最小化转义。

```ts 输入 theme={null}
"It's a string"
'He said "hello"'
`Simple string`
```

```js 输出 theme={null}
"It's a string"
'He said "hello"'
"Simple string"
```

### 数组展开内联

**模式：** `--minify-syntax`

内联带有常量数组的数组展开操作。

```ts 输入 theme={null}
[1, ...[2, 3], 4]
[...[a, b]]
```

```js 输出 theme={null}
[1,2,3,4]
[a,b]
```

### 数组索引

**模式：** `--minify-syntax`

在编译时评估常量数组访问。

```ts 输入 theme={null}
[x][0]
['a', 'b', 'c'][1]
['a', , 'c'][1]
```

```js 输出 theme={null}
x
'b'
void 0
```

### 属性访问优化

**模式：** `--minify-syntax`

在可能的情况下将方括号表示法转换为点号表示法。

```ts 输入 theme={null}
obj["property"]
obj["validName"]
obj["123"]
obj["invalid-name"]
```

```js 输出 theme={null}
obj.property
obj.validName
obj["123"]
obj["invalid-name"]
```

### 比较折叠

**模式：** `--minify-syntax`

在编译时评估常量比较。

```ts 输入 theme={null}
3 < 5
5 > 3
3 <= 3
5 >= 6
"a" < "b"
```

```js 输出 theme={null}
!0
!0
!0
!1
!0
```

### 逻辑运算折叠

**模式：** `--minify-syntax`

使用常量值简化逻辑运算。

```ts 输入 theme={null}
true && x
false && x
true || x
false || x
```

```js 输出 theme={null}
x
!1
!0
x
```

### 空值合并折叠

**模式：** `--minify-syntax`

使用已知值评估空值合并。

```ts 输入 theme={null}
null ?? x
undefined ?? x
42 ?? x
```

```js 输出 theme={null}
x
x
42
```

### 逗号表达式简化

**模式：** `--minify-syntax`

从逗号序列中移除无副作用的表达式。

```ts 输入 theme={null}
(0, x)
(123, "str", x)
```

```js 输出 theme={null}
x
x
```

### 三元条件折叠

**模式：** `--minify-syntax`

使用常量条件评估条件表达式。

```ts 输入 theme={null}
true ? a : b
false ? a : b
x ? true : false
x ? false : true
```

```js 输出 theme={null}
a
b
x ? !0 : !1
x ? !1 : !0
```

### 一元表达式折叠

**模式：** `--minify-syntax`

简化一元运算。

```ts 输入 theme={null}
+123
+"123"
-(-x)
~~x
!!x
```

```js 输出 theme={null}
123
123
- -x
~~x
!!x
```

### 双重否定移除

**模式：** `--minify-syntax`

移除不必要的双重否定。

```ts 输入 theme={null}
!!x
!!!x
```

```js 输出 theme={null}
x
!x
```

### if 语句优化

**模式：** `--minify-syntax`

使用常量条件优化 if 语句。

```ts 输入 theme={null}
if (true) x;
if (false) x;
if (x) { a; }
if (x) {} else y;
```

```js 输出 theme={null}
x;
// 已移除
if(x)a;
if(!x)y;
```

### 死代码消除

**模式：** `--minify-syntax`

移除不可达代码和无副作用的代码。

```ts 输入 theme={null}
if (false) {
  unreachable();
}
function foo() {
  return x;
  deadCode();
}
```

```js 输出 theme={null}
function foo(){return x}
```

### 不可达分支移除

**模式：** `--minify-syntax`

移除永远不会执行的分支。

```ts 输入 theme={null}
while (false) {
  neverRuns();
}
```

```js 输出 theme={null}
// 完全移除
```

### 空块移除

**模式：** `--minify-syntax`

移除空块和不必要的花括号。

```ts 输入 theme={null}
{ }
if (x) { }
```

```js 输出 theme={null}
;
// 已移除
```

### 单语句块解包

**模式：** `--minify-syntax`

移除单个语句周围的不必要花括号。

```ts 输入 theme={null}
if (condition) {
  doSomething();
}
```

```js 输出 theme={null}
if(condition)doSomething();
```

### TypeScript 枚举内联

**模式：** `--minify-syntax`

在编译时内联 TypeScript 枚举值。

```ts 输入 theme={null}
enum Color { Red, Green, Blue }
const x = Color.Red;
```

```js 输出 theme={null}
const x=0;
```

### Pure 注解支持

**模式：** 始终激活

尊重用于 tree shaking（移除未使用代码）的 `/*@__PURE__*/` 注解。

```ts 输入 theme={null}
const x = /*@__PURE__*/ expensive();
// 如果 x 未被使用...
```

```js 输出 theme={null}
// 完全移除
```

### 标识符重命名

**模式：** `--minify-identifiers`

根据使用频率将局部变量重命名为更短的名称。

```ts 输入 theme={null}
function calculateSum(firstNumber, secondNumber) {
  const result = firstNumber + secondNumber;
  return result;
}
```

```js 输出 theme={null}
function a(b,c){const d=b+c;return d}
```

**命名策略：**

* 最频繁使用的标识符获得最短名称（a、b、c……）
* 单字母：a-z（26 个名称）
* 双字母：aa-zz（676 个名称）
* 根据需要三字母及以上

**保留的标识符：**

* JavaScript 关键字和保留字
* 全局标识符
* 命名导出（以维护 API）
* CommonJS 名称：`exports`、`module`

### 空白移除

**模式：** `--minify-whitespace`

移除所有不必要的空白。

```ts 输入 theme={null}
function add(a, b) {
    return a + b;
}
let x = 10;
```

```js 输出 theme={null}
function add(a,b){return a+b;}let x=10;
```

### 分号优化

**模式：** `--minify-whitespace`

仅在必要时插入分号。

```ts 输入 theme={null}
let a = 1;
let b = 2;
return a + b;
```

```js 输出 theme={null}
let a=1;let b=2;return a+b
```

### 运算符间距移除

**模式：** `--minify-whitespace`

移除运算符周围的空格。

```ts 输入 theme={null}
a + b
x = y * z
foo && bar || baz
```

```js 输出 theme={null}
a+b
x=y*z
foo&&bar||baz
```

### 注释移除

**模式：** `--minify-whitespace`

移除注释，但保留重要的许可证注释。

```ts 输入 theme={null}
// 此注释被移除
/* 此注释也被移除 */
/*! 但此许可证注释被保留 */
function test() { /* 行内注释 */ }
```

```js 输出 theme={null}
/*! 但此许可证注释被保留 */
function test(){}
```

### 对象和数组格式化

**模式：** `--minify-whitespace`

移除对象和数组字面量中的空白。

```ts 输入 theme={null}
const obj = {
    name: "John",
    age: 30
};
const arr = [1, 2, 3];
```

```js 输出 theme={null}
const obj={name:"John",age:30};const arr=[1,2,3];
```

### 控制流格式化

**模式：** `--minify-whitespace`

移除控制结构中的空白。

```ts 输入 theme={null}
if (condition) {
    doSomething();
}
for (let i = 0; i < 10; i++) {
    console.log(i);
}
```

```js 输出 theme={null}
if(condition)doSomething();for(let i=0;i<10;i++)console.log(i);
```

### 函数格式化

**模式：** `--minify-whitespace`

移除函数声明中的空白。

```ts 输入 theme={null}
function myFunction(param1, param2) {
    return param1 + param2;
}
const arrow = (a, b) => a + b;
```

```js 输出 theme={null}
function myFunction(param1,param2){return param1+param2}const arrow=(a,b)=>a+b;
```

### 括号最小化

**模式：** 始终激活

仅在运算符优先级需要时添加括号。

```ts 输入 theme={null}
(a + b) * c
a + (b * c)
((x))
```

```js 输出 theme={null}
(a+b)*c
a+b*c
x
```

### 模板字面量值折叠

**模式：** `--minify-syntax`

将非字符串插值值转换为字符串并折叠到模板中。

```ts 输入 theme={null}
`hello ${123}`
`value: ${true}`
`result: ${null}`
`status: ${undefined}`
`big: ${10n}`
```

```js 输出 theme={null}
"hello 123"
"value: true"
"result: null"
"status: undefined"
"big: 10"
```

### 字符串长度常量折叠

**模式：** `--minify-syntax`

在编译时评估字符串字面量上的 `.length` 属性。

```ts 输入 theme={null}
"hello world".length
"test".length
```

```js 输出 theme={null}
11
4
```

### 构造函数调用简化

**模式：** `--minify-syntax`

简化内置类型的构造函数调用。

```ts 输入 theme={null}
new Object()
new Object(null)
new Object({a: 1})
new Array()
new Array(x, y)
```

```js 输出 theme={null}
{}
{}
{a:1}
[]
[x,y]
```

### 单属性对象内联

**模式：** `--minify-syntax`

内联只有一个属性的对象的属性访问。

```ts 输入 theme={null}
({fn: () => console.log('hi')}).fn
```

```js 输出 theme={null}
() => console.log('hi')
```

### 字符串 charCodeAt 常量折叠

**模式：** 始终激活

在 ASCII 字符的字符串字面量上评估 `charCodeAt()`。

```ts 输入 theme={null}
"hello".charCodeAt(1)
"A".charCodeAt(0)
```

```js 输出 theme={null}
101
65
```

### Void 0 相等转 null 相等

**模式：** `--minify-syntax`

将 `void 0` 的宽松相等检查转换为 `null`，因为它们是等价的。

```ts 输入 theme={null}
x == void 0
x != void 0
```

```js 输出 theme={null}
x == null
x != null
```

### 否定运算符优化

**模式：** `--minify-syntax`

将否定运算符移过逗号表达式。

```ts 输入 theme={null}
-(a, b)
-(x, y, z)
```

```js 输出 theme={null}
a,-b
x,y,-z
```

### Import.meta 属性内联

**模式：** 打包模式

在知道值时于构建时内联 `import.meta` 属性。

```ts 输入 theme={null}
import.meta.dir
import.meta.file
import.meta.path
import.meta.url
```

```js 输出 theme={null}
"/path/to/directory"
"filename.js"
"/full/path/to/file.js"
"file:///full/path/to/file.js"
```

### 变量声明合并

**模式：** `--minify-syntax`

合并同类型相邻的变量声明。

```ts 输入 theme={null}
let a = 1;
let b = 2;
const c = 3;
const d = 4;
```

```js 输出 theme={null}
let a=1,b=2;
const c=3,d=4;
```

### 表达式语句合并

**模式：** `--minify-syntax`

使用逗号运算符合并相邻的表达式语句。

```ts 输入 theme={null}
console.log(1);
console.log(2);
console.log(3);
```

```js 输出 theme={null}
console.log(1),console.log(2),console.log(3);
```

### return 语句合并

**模式：** `--minify-syntax`

使用逗号运算符合并 return 前的表达式。

```ts 输入 theme={null}
console.log(x);
return y;
```

```js 输出 theme={null}
return console.log(x),y;
```

### throw 语句合并

**模式：** `--minify-syntax`

使用逗号运算符合并 throw 前的表达式。

```ts 输入 theme={null}
console.log(x);
throw new Error();
```

```js 输出 theme={null}
throw(console.log(x),new Error());
```

### TypeScript 枚举跨模块内联

**模式：** `--minify-syntax`（打包模式）

跨模块边界内联枚举值。

```ts 输入 theme={null}
// lib.ts
export enum Color { Red, Green, Blue }

// 输入（main.ts）
import { Color } from './lib';
const x = Color.Red;
```

```js 输出 theme={null}
const x=0;
```

### 计算属性枚举内联

**模式：** `--minify-syntax`

内联用作计算对象属性的枚举值。

```ts 输入 theme={null}
enum Keys { FOO = 'foo' }
const obj = { [Keys.FOO]: value }
```

```js 输出 theme={null}
const obj={foo:value}
```

### 箭头函数体缩短

**模式：** `--minify-syntax`

当箭头函数只返回一个值时使用表达式体语法。

```ts 输入 theme={null}
() => { return x; }
(a) => { return a + 1; }
```

```js 输出 theme={null}
() => x
a => a + 1
```

### 对象属性简写

**模式：** 始终激活

当属性名和值标识符匹配时使用简写语法。

```ts 输入 theme={null}
{ x: x, y: y }
{ name: name, age: age }
```

```js 输出 theme={null}
{ x, y }
{ name, age }
```

### 丢弃 debugger 语句

**模式：** `--drop=debugger`

从代码中移除 `debugger` 语句。

```ts 输入 theme={null}
function test() {
  debugger;
  return x;
}
```

```js 输出 theme={null}
function test(){return x}
```

### 丢弃 console 调用

**模式：** `--drop=console`

从代码中移除所有 `console.*` 方法调用。

```ts 输入 theme={null}
console.log("debug");
console.warn("warning");
x = console.error("error");
```

```js 输出 theme={null}
void 0;
void 0;
x=void 0;
```

### 丢弃自定义函数调用

**模式：** `--drop=<name>`

移除对指定全局函数及其方法的调用。

```ts 输入 theme={null}
assert(condition);
assert.equal(a, b);
```

```js 使用 --drop=assert 输出 theme={null}
void 0;
void 0;
```

## 保留名称

要在压缩标识符时保留原始函数和类名以便调试，使用 `--keep-names` 标志：

```bash theme={null}
bun build ./index.ts --minify --keep-names --outfile=out.js
```

或在 JavaScript API 中：

```ts theme={null}
await Bun.build({
  entrypoints: ["./index.ts"],
  outdir: "./out",
  minify: {
    identifiers: true,
    keepNames: true,
  },
});
```

`--keep-names` 保留函数和类上的 `.name` 属性，同时仍然压缩标识符本身。

## 组合示例

同时使用所有三种压缩模式：

```ts input.ts (158 bytes) theme={null}
const myVariable = 42;

const myFunction = () => {
  const isValid = true;
  const result = undefined;
  return isValid ? myVariable : result;
};

const output = myFunction();
```

```js output.js theme={null}
// 使用 --minify 输出（49 bytes，减少 69%）
const a=42,b=()=>{const c=!0,d=void 0;return c?a:d},e=b();
```

## 何时使用压缩

**对以下场景使用 `--minify`：**

* 生产包
* 减少 CDN 带宽成本
* 改善页面加载时间

**对以下场景使用单独模式：**

* **`--minify-whitespace`：** 在不改变语义的情况下减小体积
* **`--minify-syntax`：** 减小输出，同时保留可读标识符以便调试
* **`--minify-identifiers`：** 最大体积缩减（与 `--keep-names` 结合以获得更好的堆栈跟踪）

**应避免压缩的场景：**

* 开发构建（更难调试）
* 需要可读错误消息时
* 消费者可能阅读源代码的库
