Skip to content

Bun 包含一個快速的 JavaScript 和 TypeScript 壓縮器,可以將包大小減少 80% 或更多(取決於代碼庫),並使輸出代碼運行更快。壓縮器執行數十種優化,包括常量折疊、死代碼消除和語法轉換。與其他壓縮器不同,Bun 的壓縮器使 bun build 運行更快,因為要打印的代碼更少。

CLI 使用

啟用所有壓縮模式

使用 --minify 標志啟用所有壓縮模式:

bash
bun build ./index.ts --minify --outfile=out.js

--minify 標志自動啟用:

  • 空白壓縮
  • 語法壓縮
  • 標識符壓縮

生產模式

--production 標志自動啟用壓縮:

bash
bun build ./index.ts --production --outfile=out.js

--production 標志還:

  • process.env.NODE_ENV 設置為 production
  • 啟用生產模式 JSX 導入和轉換

細粒度控制

您可以單獨啟用特定的壓縮模式:

bash
# 僅移除空白
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
await Bun.build({
  entrypoints: ["./index.ts"],
  outdir: "./out",
  minify: true, // 啟用所有壓縮模式
});

對於細粒度控制,傳遞對象:

ts
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
true
false
js
!0
!1

布爾代數優化

模式: --minify-syntax

使用邏輯規則簡化布爾表達式。

ts
!!x
x === true
x && true
x || false
!true
!false
js
x
x
x
x
!1
!0

undefined 縮短

模式: --minify-syntax

undefined 替換為更短的等效形式。

ts
undefined
let x = undefined;
js
void 0
let x=void 0;

undefined 相等優化

模式: --minify-syntax

優化與 undefined 的松散相等檢查。

ts
x == undefined
x != undefined
js
x == null
x != null

Infinity 縮短

模式: --minify-syntax

將 Infinity 轉換為數學表達式。

ts
Infinity
-Infinity
js
1/0
-1/0

Typeof 優化

模式: --minify-syntax

優化 typeof 比較並評估常量 typeof 表達式。

ts
typeof x === 'undefined'
typeof x !== 'undefined'
typeof require
typeof null
typeof true
typeof 123
typeof "str"
typeof 123n
js
typeof x>'u'
typeof x<'u'
"function"
"object"
"boolean"
"number"
"string"
"bigint"

數字格式化

模式: --minify-syntax

以最緊湊的表示形式格式化數字。

ts
10000
100000
1000000
1.0
-42.0
js
1e4
1e5
1e6
1
-42

算術常量折疊

模式: --minify-syntax

在編譯時評估算術運算。

ts
1 + 2
10 - 5
3 * 4
10 / 2
10 % 3
2 ** 3
js
3
5
12
5
1
8

位運算常量折疊

模式: --minify-syntax

在編譯時評估位運算。

ts
5 & 3
5 | 3
5 ^ 3
8 << 2
32 >> 2
~5
js
1
7
6
32
8
-6

字符串連接

模式: --minify-syntax

在編譯時組合字符串字面量。

ts
"a" + "b"
"x" + 123
"foo" + "bar" + "baz"
js
"ab"
"x123"
"foobarbaz"

字符串索引

模式: --minify-syntax

在編譯時評估字符串字符訪問。

ts
"foo"[2]
"hello"[0]
js
"o"
"h"

模板字面量折疊

模式: --minify-syntax

評估帶有常量表達式的模板字面量。

ts
`a${123}b`
`result: ${5 + 10}`
js
"a123b"
"result: 15"

模板字面量轉換為字符串

模式: --minify-syntax

將簡單模板字面量轉換為常規字符串。

ts
`Hello World`
`Line 1
Line 2`
js
"Hello World"
"Line 1\nLine 2"

字符串引號優化

模式: --minify-syntax

選擇最佳引號字符以最小化轉義。

ts
"It's a string"
'He said "hello"'
`Simple string`
js
"It's a string"
'He said "hello"'
"Simple string"

數組展開內聯

模式: --minify-syntax

內聯帶有常量數組的數組展開操作。

ts
[1, ...[2, 3], 4]
[...[a, b]]
js
[1,2,3,4]
[a,b]

數組索引

模式: --minify-syntax

在編譯時評估常量數組訪問。

ts
[x][0]
['a', 'b', 'c'][1]
['a', , 'c'][1]
js
x
'b'
void 0

屬性訪問優化

模式: --minify-syntax

在可能時將方括號表示法轉換為點表示法。

ts
obj["property"]
obj["validName"]
obj["123"]
obj["invalid-name"]
js
obj.property
obj.validName
obj["123"]
obj["invalid-name"]

比較折疊

模式: --minify-syntax

在編譯時評估常量比較。

ts
3 < 5
5 > 3
3 <= 3
5 >= 6
"a" < "b"
js
!0
!0
!0
!1
!0

邏輯運算折疊

模式: --minify-syntax

使用常量值簡化邏輯運算。

ts
true && x
false && x
true || x
false || x
js
x
!1
!0
x

空值合並折疊

模式: --minify-syntax

評估具有已知值的空值合並。

ts
null ?? x
undefined ?? x
42 ?? x
js
x
x
42

逗號表達式簡化

模式: --minify-syntax

從逗號序列中移除無副作用的表達式。

ts
(0, x)
(123, "str", x)
js
x
x

三元條件折疊

模式: --minify-syntax

評估具有常量條件的條件表達式。

ts
true ? a : b
false ? a : b
x ? true : false
x ? false : true
js
a
b
x ? !0 : !1
x ? !1 : !0

一元表達式折疊

模式: --minify-syntax

簡化一元運算。

ts
+123
+"123"
-(-x)
~~x
!!x
js
123
123
123
123
x
~~x
!!x
x

雙重否定移除

模式: --minify-syntax

移除不必要的雙重否定。

ts
!!x
!!!x
js
x
!x

if 語句優化

模式: --minify-syntax

優化具有常量條件的 if 語句。

ts
if (true) x;
if (false) x;
if (x) { a; }
if (x) {} else y;
js
x;
// 已移除
if(x)a;
if(!x)y;

死代碼消除

模式: --minify-syntax

移除不可達代碼和無副作用的代碼。

ts
if (false) {
  unreachable();
}
function foo() {
  return x;
  deadCode();
}
js
function foo(){return x}

不可達分支移除

模式: --minify-syntax

移除永遠不會執行的分支。

ts
while (false) {
  neverRuns();
}
js
// 完全移除

空塊移除

模式: --minify-syntax

移除空塊和不必要的大括號。

ts
{ }
if (x) { }
js
;
// 已移除

單語句塊展開

模式: --minify-syntax

移除單個語句周圍不必要的大括號。

ts
if (condition) {
  doSomething();
}
js
if(condition)doSomething();

TypeScript 枚舉內聯

模式: --minify-syntax

在編譯時內聯 TypeScript 枚舉值。

ts
enum Color { Red, Green, Blue }
const x = Color.Red;
js
const x=0;

純注釋支持

模式: 始終激活

尊重 /*@__PURE__*/ 注釋用於 tree shaking。

ts
const x = /*@__PURE__*/ expensive();
// 如果 x 未使用...
js
// 完全移除

標識符重命名

模式: --minify-identifiers

根據使用頻率將局部變量重命名為更短的名稱。

ts
function calculateSum(firstNumber, secondNumber) {
  const result = firstNumber + secondNumber;
  return result;
}
js
function a(b,c){const d=b+c;return d}

命名策略:

  • 最常用的標識符獲得最短的名稱(a、b、c...)
  • 單個字母:a-z(26 個名稱)
  • 雙字母:aa-zz(676 個名稱)
  • 三字母及更多按需使用

保留的標識符:

  • JavaScript 關鍵字和保留字
  • 全局標識符
  • 命名導出(維護 API)
  • CommonJS 名稱:exportsmodule

空白移除

模式: --minify-whitespace

移除所有不必要的空白。

ts
function add(a, b) {
    return a + b;
}
let x = 10;
js
function add(a,b){return a+b;}let x=10;

分號優化

模式: --minify-whitespace

僅在必要時插入分號。

ts
let a = 1;
let b = 2;
return a + b;
js
let a=1;let b=2;return a+b

運算符間距移除

模式: --minify-whitespace

移除運算符周圍的空格。

ts
a + b
x = y * z
foo && bar || baz
js
a+b
x=y*z
foo&&bar||baz

注釋移除

模式: --minify-whitespace

移除注釋,重要的許可證注釋除外。

ts
// 此注釋被移除
/* 此注釋也被移除 */
/*! 但此許可證注釋保留 */
function test() { /* 內聯注釋 */ }
js
/*! 但此許可證注釋保留 */
function test(){}

對象和數組格式化

模式: --minify-whitespace

移除對象和數組字面量中的空白。

ts
const obj = {
    name: "John",
    age: 30
};
const arr = [1, 2, 3];
js
const obj={name:"John",age:30};const arr=[1,2,3];

控制流格式化

模式: --minify-whitespace

移除控制結構中的空白。

ts
if (condition) {
    doSomething();
}
for (let i = 0; i < 10; i++) {
    console.log(i);
}
js
if(condition)doSomething();for(let i=0;i<10;i++)console.log(i);

函數格式化

模式: --minify-whitespace

移除函數聲明中的空白。

ts
function myFunction(param1, param2) {
    return param1 + param2;
}
const arrow = (a, b) => a + b;
js
function myFunction(a,b){return a+b}const arrow=(a,b)=>a+b;

括號最小化

模式: 始終激活

僅在運算符優先級需要時添加括號。

ts
(a + b) * c
a + (b * c)
((x))
js
(a+b)*c
a+b*c
x

屬性混淆

模式: --minify-identifiers(帶配置)

在配置時將對象屬性重命名為更短的名稱。

ts
obj.longPropertyName
js
obj.a

模板字面量值折疊

模式: --minify-syntax

將非字符串插值值轉換為字符串並折疊到模板中。

ts
`hello ${123}`
`value: ${true}`
`result: ${null}`
`status: ${undefined}`
`big: ${10n}`
js
"hello 123"
"value: true"
"result: null"
"status: undefined"
"big: 10"

字符串長度常量折疊

模式: --minify-syntax

在編譯時評估字符串字面量上的 .length 屬性。

ts
"hello world".length
"test".length
js
11
4

構造函數調用簡化

模式: --minify-syntax

簡化內置類型的構造函數調用。

ts
new Object()
new Object(null)
new Object({a: 1})
new Array()
new Array(x, y)
js
{}
{}
{a:1}
[]
[x,y]

單屬性對象內聯

模式: --minify-syntax

內聯具有單個屬性的對象的屬性訪問。

ts
({fn: () => console.log('hi')}).fn()
js
(() => console.log('hi'))()

字符串 charCodeAt 常量折疊

模式: 始終激活

評估字符串字面量上的 charCodeAt() 用於 ASCII 字符。

ts
"hello".charCodeAt(1)
"A".charCodeAt(0)
js
101
65

Void 0 相等轉換為 null 相等

模式: --minify-syntax

將與 void 0 的松散相等檢查轉換為 null,因為它們是等效的。

ts
x == void 0
x != void 0
js
x == null
x != null

否定運算符優化

模式: --minify-syntax

將否定運算符移過逗號表達式。

ts
-(a, b)
-(x, y, z)
js
a,-b
x,y,-z

Import.meta 屬性內聯

模式: 打包模式

在構建時在值已知時內聯 import.meta 屬性。

ts
import.meta.dir
import.meta.file
import.meta.path
import.meta.url
js
"/path/to/directory"
"filename.js"
"/full/path/to/file.js"
"file:///full/path/to/file.js"

變量聲明合並

模式: --minify-syntax

合並相同類型的相鄰變量聲明。

ts
let a = 1;
let b = 2;
const c = 3;
const d = 4;
js
let a=1,b=2;
const c=3,d=4;

表達式語句合並

模式: --minify-syntax

使用逗號運算符合並相鄰表達式語句。

ts
console.log(1);
console.log(2);
console.log(3);
js
console.log(1),console.log(2),console.log(3);

return 語句合並

模式: --minify-syntax

使用逗號運算符合並 return 之前的表達式。

ts
console.log(x);
return y;
js
return console.log(x),y;

throw 語句合並

模式: --minify-syntax

使用逗號運算符合並 throw 之前的表達式。

ts
console.log(x);
throw new Error();
js
throw(console.log(x),new Error());

TypeScript 枚舉跨模塊內聯

模式: --minify-syntax(打包模式)

跨模塊邊界內聯枚舉值。

ts
// lib.ts
export enum Color { Red, Green, Blue }

// 輸入 (main.ts)
import { Color } from './lib';
const x = Color.Red;
js
const x=0;

計算屬性枚舉內聯

模式: --minify-syntax

內聯用作計算對象屬性的枚舉值。

ts
enum Keys { FOO = 'foo' }
const obj = { [Keys.FOO]: value }
js
const obj={foo:value}

字符串數字轉換為數字索引

模式: --minify-syntax

將字符串數字屬性訪問轉換為數字索引。

ts
obj["0"]
arr["5"]
js
obj[0]
arr[5]

箭頭函數體縮短

模式: 始終激活

當箭頭函數僅返回值時使用表達式體語法。

ts
() => { return x; }
(a) => { return a + 1; }
js
() => x
a => a + 1

對象屬性簡寫

模式: 始終激活

當屬性名和值標識符匹配時使用簡寫語法。

ts
{ x: x, y: y }
{ name: name, age: age }
js
{ x, y }
{ name, age }

方法簡寫

模式: 始終激活

在對象字面量中使用方法簡寫語法。

ts
{
  foo: function() {},
  bar: async function() {}
}
js
{
  foo() {},
  async bar() {}
}

移除 debugger 語句

模式: --drop=debugger

從代碼中移除 debugger 語句。

ts
function test() {
  debugger;
  return x;
}
js
function test(){return x}

移除 console 調用

模式: --drop=console

從代碼中移除所有 console.* 方法調用。

ts
console.log("debug");
console.warn("warning");
x = console.error("error");
js
void 0;
void 0;
x=void 0;

移除自定義函數調用

模式: --drop=<name>

移除對指定全局函數或方法的調用。

ts
assert(condition);
obj.assert(test);
js
void 0;
void 0;

保留名稱

壓縮標識符時,您可能希望保留原始函數和類名以便調試。使用 --keep-names 標志:

bash
bun build ./index.ts --minify --keep-names --outfile=out.js

或在 JavaScript API 中:

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

這在仍然壓縮代碼中實際標識符名稱的同時保留函數和類上的 .name 屬性。

組合示例

一起使用所有三種壓縮模式:

ts
const myVariable = 42;

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

const output = myFunction();
js
// 使用 --minify 輸出(49 字節,減少 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 組合以獲得更好的堆棧跟蹤)

避免壓縮:

  • 開發構建(更難調試)
  • 當您需要可讀錯誤消息時
  • 消費者可能閱讀源代碼的庫

Bun學習網由www.bunjs.com.cn整理維護