Bun 包含一個快速的 JavaScript 和 TypeScript 壓縮器,可以將包大小減少 80% 或更多(取決於代碼庫),並使輸出代碼運行更快。壓縮器執行數十種優化,包括常量折疊、死代碼消除和語法轉換。與其他壓縮器不同,Bun 的壓縮器使 bun build 運行更快,因為要打印的代碼更少。
CLI 使用
啟用所有壓縮模式
使用 --minify 標志啟用所有壓縮模式:
bun build ./index.ts --minify --outfile=out.js--minify 標志自動啟用:
- 空白壓縮
- 語法壓縮
- 標識符壓縮
生產模式
--production 標志自動啟用壓縮:
bun build ./index.ts --production --outfile=out.js--production 標志還:
- 將
process.env.NODE_ENV設置為production - 啟用生產模式 JSX 導入和轉換
細粒度控制
您可以單獨啟用特定的壓縮模式:
# 僅移除空白
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.jsJavaScript API
以編程方式使用 Bun 的打包器時,通過 minify 選項配置壓縮:
await Bun.build({
entrypoints: ["./index.ts"],
outdir: "./out",
minify: true, // 啟用所有壓縮模式
});對於細粒度控制,傳遞對象:
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
將布爾字面量轉換為更短的表達式。
true
false!0
!1布爾代數優化
模式: --minify-syntax
使用邏輯規則簡化布爾表達式。
!!x
x === true
x && true
x || false
!true
!falsex
x
x
x
!1
!0undefined 縮短
模式: --minify-syntax
將 undefined 替換為更短的等效形式。
undefined
let x = undefined;void 0
let x=void 0;undefined 相等優化
模式: --minify-syntax
優化與 undefined 的松散相等檢查。
x == undefined
x != undefinedx == null
x != nullInfinity 縮短
模式: --minify-syntax
將 Infinity 轉換為數學表達式。
Infinity
-Infinity1/0
-1/0Typeof 優化
模式: --minify-syntax
優化 typeof 比較並評估常量 typeof 表達式。
typeof x === 'undefined'
typeof x !== 'undefined'
typeof require
typeof null
typeof true
typeof 123
typeof "str"
typeof 123ntypeof x>'u'
typeof x<'u'
"function"
"object"
"boolean"
"number"
"string"
"bigint"數字格式化
模式: --minify-syntax
以最緊湊的表示形式格式化數字。
10000
100000
1000000
1.0
-42.01e4
1e5
1e6
1
-42算術常量折疊
模式: --minify-syntax
在編譯時評估算術運算。
1 + 2
10 - 5
3 * 4
10 / 2
10 % 3
2 ** 33
5
12
5
1
8位運算常量折疊
模式: --minify-syntax
在編譯時評估位運算。
5 & 3
5 | 3
5 ^ 3
8 << 2
32 >> 2
~51
7
6
32
8
-6字符串連接
模式: --minify-syntax
在編譯時組合字符串字面量。
"a" + "b"
"x" + 123
"foo" + "bar" + "baz""ab"
"x123"
"foobarbaz"字符串索引
模式: --minify-syntax
在編譯時評估字符串字符訪問。
"foo"[2]
"hello"[0]"o"
"h"模板字面量折疊
模式: --minify-syntax
評估帶有常量表達式的模板字面量。
`a${123}b`
`result: ${5 + 10}`"a123b"
"result: 15"模板字面量轉換為字符串
模式: --minify-syntax
將簡單模板字面量轉換為常規字符串。
`Hello World`
`Line 1
Line 2`"Hello World"
"Line 1\nLine 2"字符串引號優化
模式: --minify-syntax
選擇最佳引號字符以最小化轉義。
"It's a string"
'He said "hello"'
`Simple string`"It's a string"
'He said "hello"'
"Simple string"數組展開內聯
模式: --minify-syntax
內聯帶有常量數組的數組展開操作。
[1, ...[2, 3], 4]
[...[a, b]][1,2,3,4]
[a,b]數組索引
模式: --minify-syntax
在編譯時評估常量數組訪問。
[x][0]
['a', 'b', 'c'][1]
['a', , 'c'][1]x
'b'
void 0屬性訪問優化
模式: --minify-syntax
在可能時將方括號表示法轉換為點表示法。
obj["property"]
obj["validName"]
obj["123"]
obj["invalid-name"]obj.property
obj.validName
obj["123"]
obj["invalid-name"]比較折疊
模式: --minify-syntax
在編譯時評估常量比較。
3 < 5
5 > 3
3 <= 3
5 >= 6
"a" < "b"!0
!0
!0
!1
!0邏輯運算折疊
模式: --minify-syntax
使用常量值簡化邏輯運算。
true && x
false && x
true || x
false || xx
!1
!0
x空值合並折疊
模式: --minify-syntax
評估具有已知值的空值合並。
null ?? x
undefined ?? x
42 ?? xx
x
42逗號表達式簡化
模式: --minify-syntax
從逗號序列中移除無副作用的表達式。
(0, x)
(123, "str", x)x
x三元條件折疊
模式: --minify-syntax
評估具有常量條件的條件表達式。
true ? a : b
false ? a : b
x ? true : false
x ? false : truea
b
x ? !0 : !1
x ? !1 : !0一元表達式折疊
模式: --minify-syntax
簡化一元運算。
+123
+"123"
-(-x)
~~x
!!x123
123
123
123
x
~~x
!!x
x雙重否定移除
模式: --minify-syntax
移除不必要的雙重否定。
!!x
!!!xx
!xif 語句優化
模式: --minify-syntax
優化具有常量條件的 if 語句。
if (true) x;
if (false) x;
if (x) { a; }
if (x) {} else y;x;
// 已移除
if(x)a;
if(!x)y;死代碼消除
模式: --minify-syntax
移除不可達代碼和無副作用的代碼。
if (false) {
unreachable();
}
function foo() {
return x;
deadCode();
}function foo(){return x}不可達分支移除
模式: --minify-syntax
移除永遠不會執行的分支。
while (false) {
neverRuns();
}// 完全移除空塊移除
模式: --minify-syntax
移除空塊和不必要的大括號。
{ }
if (x) { };
// 已移除單語句塊展開
模式: --minify-syntax
移除單個語句周圍不必要的大括號。
if (condition) {
doSomething();
}if(condition)doSomething();TypeScript 枚舉內聯
模式: --minify-syntax
在編譯時內聯 TypeScript 枚舉值。
enum Color { Red, Green, Blue }
const x = Color.Red;const x=0;純注釋支持
模式: 始終激活
尊重 /*@__PURE__*/ 注釋用於 tree shaking。
const x = /*@__PURE__*/ expensive();
// 如果 x 未使用...// 完全移除標識符重命名
模式: --minify-identifiers
根據使用頻率將局部變量重命名為更短的名稱。
function calculateSum(firstNumber, secondNumber) {
const result = firstNumber + secondNumber;
return result;
}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
移除所有不必要的空白。
function add(a, b) {
return a + b;
}
let x = 10;function add(a,b){return a+b;}let x=10;分號優化
模式: --minify-whitespace
僅在必要時插入分號。
let a = 1;
let b = 2;
return a + b;let a=1;let b=2;return a+b運算符間距移除
模式: --minify-whitespace
移除運算符周圍的空格。
a + b
x = y * z
foo && bar || baza+b
x=y*z
foo&&bar||baz注釋移除
模式: --minify-whitespace
移除注釋,重要的許可證注釋除外。
// 此注釋被移除
/* 此注釋也被移除 */
/*! 但此許可證注釋保留 */
function test() { /* 內聯注釋 */ }/*! 但此許可證注釋保留 */
function test(){}對象和數組格式化
模式: --minify-whitespace
移除對象和數組字面量中的空白。
const obj = {
name: "John",
age: 30
};
const arr = [1, 2, 3];const obj={name:"John",age:30};const arr=[1,2,3];控制流格式化
模式: --minify-whitespace
移除控制結構中的空白。
if (condition) {
doSomething();
}
for (let i = 0; i < 10; i++) {
console.log(i);
}if(condition)doSomething();for(let i=0;i<10;i++)console.log(i);函數格式化
模式: --minify-whitespace
移除函數聲明中的空白。
function myFunction(param1, param2) {
return param1 + param2;
}
const arrow = (a, b) => a + b;function myFunction(a,b){return a+b}const arrow=(a,b)=>a+b;括號最小化
模式: 始終激活
僅在運算符優先級需要時添加括號。
(a + b) * c
a + (b * c)
((x))(a+b)*c
a+b*c
x屬性混淆
模式: --minify-identifiers(帶配置)
在配置時將對象屬性重命名為更短的名稱。
obj.longPropertyNameobj.a模板字面量值折疊
模式: --minify-syntax
將非字符串插值值轉換為字符串並折疊到模板中。
`hello ${123}`
`value: ${true}`
`result: ${null}`
`status: ${undefined}`
`big: ${10n}`"hello 123"
"value: true"
"result: null"
"status: undefined"
"big: 10"字符串長度常量折疊
模式: --minify-syntax
在編譯時評估字符串字面量上的 .length 屬性。
"hello world".length
"test".length11
4構造函數調用簡化
模式: --minify-syntax
簡化內置類型的構造函數調用。
new Object()
new Object(null)
new Object({a: 1})
new Array()
new Array(x, y){}
{}
{a:1}
[]
[x,y]單屬性對象內聯
模式: --minify-syntax
內聯具有單個屬性的對象的屬性訪問。
({fn: () => console.log('hi')}).fn()(() => console.log('hi'))()字符串 charCodeAt 常量折疊
模式: 始終激活
評估字符串字面量上的 charCodeAt() 用於 ASCII 字符。
"hello".charCodeAt(1)
"A".charCodeAt(0)101
65Void 0 相等轉換為 null 相等
模式: --minify-syntax
將與 void 0 的松散相等檢查轉換為 null,因為它們是等效的。
x == void 0
x != void 0x == null
x != null否定運算符優化
模式: --minify-syntax
將否定運算符移過逗號表達式。
-(a, b)
-(x, y, z)a,-b
x,y,-zImport.meta 屬性內聯
模式: 打包模式
在構建時在值已知時內聯 import.meta 屬性。
import.meta.dir
import.meta.file
import.meta.path
import.meta.url"/path/to/directory"
"filename.js"
"/full/path/to/file.js"
"file:///full/path/to/file.js"變量聲明合並
模式: --minify-syntax
合並相同類型的相鄰變量聲明。
let a = 1;
let b = 2;
const c = 3;
const d = 4;let a=1,b=2;
const c=3,d=4;表達式語句合並
模式: --minify-syntax
使用逗號運算符合並相鄰表達式語句。
console.log(1);
console.log(2);
console.log(3);console.log(1),console.log(2),console.log(3);return 語句合並
模式: --minify-syntax
使用逗號運算符合並 return 之前的表達式。
console.log(x);
return y;return console.log(x),y;throw 語句合並
模式: --minify-syntax
使用逗號運算符合並 throw 之前的表達式。
console.log(x);
throw new Error();throw(console.log(x),new Error());TypeScript 枚舉跨模塊內聯
模式: --minify-syntax(打包模式)
跨模塊邊界內聯枚舉值。
// lib.ts
export enum Color { Red, Green, Blue }
// 輸入 (main.ts)
import { Color } from './lib';
const x = Color.Red;const x=0;計算屬性枚舉內聯
模式: --minify-syntax
內聯用作計算對象屬性的枚舉值。
enum Keys { FOO = 'foo' }
const obj = { [Keys.FOO]: value }const obj={foo:value}字符串數字轉換為數字索引
模式: --minify-syntax
將字符串數字屬性訪問轉換為數字索引。
obj["0"]
arr["5"]obj[0]
arr[5]箭頭函數體縮短
模式: 始終激活
當箭頭函數僅返回值時使用表達式體語法。
() => { return x; }
(a) => { return a + 1; }() => x
a => a + 1對象屬性簡寫
模式: 始終激活
當屬性名和值標識符匹配時使用簡寫語法。
{ x: x, y: y }
{ name: name, age: age }{ x, y }
{ name, age }方法簡寫
模式: 始終激活
在對象字面量中使用方法簡寫語法。
{
foo: function() {},
bar: async function() {}
}{
foo() {},
async bar() {}
}移除 debugger 語句
模式: --drop=debugger
從代碼中移除 debugger 語句。
function test() {
debugger;
return x;
}function test(){return x}移除 console 調用
模式: --drop=console
從代碼中移除所有 console.* 方法調用。
console.log("debug");
console.warn("warning");
x = console.error("error");void 0;
void 0;
x=void 0;移除自定義函數調用
模式: --drop=<name>
移除對指定全局函數或方法的調用。
assert(condition);
obj.assert(test);void 0;
void 0;保留名稱
壓縮標識符時,您可能希望保留原始函數和類名以便調試。使用 --keep-names 標志:
bun build ./index.ts --minify --keep-names --outfile=out.js或在 JavaScript API 中:
await Bun.build({
entrypoints: ["./index.ts"],
outdir: "./out",
minify: {
identifiers: true,
keepNames: true,
},
});這在仍然壓縮代碼中實際標識符名稱的同時保留函數和類上的 .name 屬性。
組合示例
一起使用所有三種壓縮模式:
const myVariable = 42;
const myFunction = () => {
const isValid = true;
const result = undefined;
return isValid ? myVariable : result;
};
const output = myFunction();// 使用 --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組合以獲得更好的堆棧跟蹤)
避免壓縮:
- 開發構建(更難調試)
- 當您需要可讀錯誤消息時
- 消費者可能閱讀源代碼的庫