bun-cli

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Bun CLI

Bun CLI

Bun is an all-in-one JavaScript/TypeScript runtime, package manager, bundler, and test runner. Bun runs TypeScript natively —
bun file.ts
directly, no compile step, no
tsc
, no
ts-node
. Always use
bun
instead of
node
,
npm
,
npx
,
yarn
, or
pnpm
in Bun projects.
Verified against Bun v1.3.14 (2026-05-28).
Bun 是一款一体化的 JavaScript/TypeScript 运行时、包管理器、打包工具和测试运行器。Bun 原生支持 TypeScript——直接运行
bun file.ts
,无需编译步骤,无需
tsc
,无需
ts-node
。在 Bun 项目中,请始终使用
bun
替代
node
npm
npx
yarn
pnpm
已针对 Bun v1.3.14 验证(2026-05-28)。

Detecting Bun Projects

识别 Bun 项目

A project uses Bun if any of these are present:
  • bun.lock
    or
    bun.lockb
    in the project root
  • bunfig.toml
    in the project root
  • bun
    field in
    package.json
    (e.g.,
    "bun": { "install": { ... } }
    )
  • Package manager field:
    "packageManager": "bun@..."
  • [run] bun = true
    in
    bunfig.toml
    (forces Bun runtime for all scripts)
如果项目中存在以下任一内容,则表明该项目使用 Bun:
  • 项目根目录下的
    bun.lock
    bun.lockb
  • 项目根目录下的
    bunfig.toml
  • package.json
    中的
    bun
    字段(例如:
    "bun": { "install": { ... } }
  • 包管理器字段:
    "packageManager": "bun@..."
  • bunfig.toml
    中的
    [run] bun = true
    (强制所有脚本使用 Bun 运行时)

Critical Rule

关键规则

In a Bun project, ALWAYS use
bun
for everything.
Never fall back to
node
,
npm
,
npx
,
yarn
, or
pnpm
. This avoids compatibility issues, unnecessary retries, and cryptic errors from Node.js/npm not understanding Bun-specific features (workspace protocol, lockfile format, trustedDependencies, etc.).
  • Run files:
    bun file.ts
    (not
    node file.ts
    )
  • Run scripts:
    bun run dev
    (not
    npm run dev
    )
  • Execute binaries:
    bunx tool
    (not
    npx tool
    )
  • Install packages:
    bun add pkg
    (not
    npm install pkg
    )
  • Run tests:
    bun test
    (not
    npx jest
    or
    node --test
    )
在 Bun 项目中,所有操作都必须使用
bun
。永远不要回退使用
node
npm
npx
yarn
pnpm
。这可以避免兼容性问题、不必要的重试,以及 Node.js/npm 无法理解 Bun 特定功能(工作区协议、锁文件格式、trustedDependencies 等)导致的晦涩错误。
  • 运行文件:
    bun file.ts
    (而非
    node file.ts
  • 运行脚本:
    bun run dev
    (而非
    npm run dev
  • 执行二进制文件:
    bunx tool
    (而非
    npx tool
  • 安装包:
    bun add pkg
    (而非
    npm install pkg
  • 运行测试:
    bun test
    (而非
    npx jest
    node --test

Read-Only Commands (safe, no side effects)

只读命令(安全,无副作用)

CommandPurpose
bun --version
Runtime version
bun info <pkg>
Package metadata, available versions
bun info <pkg> versions
List all published versions
bun pm ls
List installed packages
bun pm ls --all
List all (including transitive)
bun pm hash
Print lockfile hash
bun pm cache
Show cache directory
bun outdated
Check for outdated dependencies
bun audit
Security vulnerability audit
bun test
Run test suite
bun run lint
Run linter (project-specific)
bun run check-types
Type checking (project-specific)
Reference: See
references/allowlist.md
for copy-paste
Bash(command:*)
patterns for Claude Code / OpenCode settings.
命令用途
bun --version
查看运行时版本
bun info <pkg>
查看包元数据、可用版本
bun info <pkg> versions
列出所有已发布版本
bun pm ls
列出已安装的包
bun pm ls --all
列出所有包(包括间接依赖)
bun pm hash
打印锁文件哈希值
bun pm cache
显示缓存目录
bun outdated
检查过时依赖
bun audit
安全漏洞审计
bun test
运行测试套件
bun run lint
运行代码检查工具(项目特定)
bun run check-types
类型检查(项目特定)
参考:查看
references/allowlist.md
获取可复制粘贴到 Claude Code / OpenCode 设置中的
Bash(command:*)
模式。

npm/npx/node to Bun Translation

npm/npx/node 到 Bun 的命令映射

npm/npx/nodeBun equivalent
npm install
bun install
npm install pkg
bun add pkg
npm install -D pkg
bun add -d pkg
npm install -g pkg
bun add -g pkg
npm uninstall pkg
bun remove pkg
npm update
bun update
npm run script
bun run script
npx command
bunx command
node file.js
bun file.js
node --watch file.js
bun --watch file.js
npm test
bun test
npm pack
bun pm pack
npm publish
bun publish
npm info pkg
bun info pkg
npm outdated
bun outdated
npm audit
bun audit
npm link
bun link
npm/npx/nodeBun 等效命令
npm install
bun install
npm install pkg
bun add pkg
npm install -D pkg
bun add -d pkg
npm install -g pkg
bun add -g pkg
npm uninstall pkg
bun remove pkg
npm update
bun update
npm run script
bun run script
npx command
bunx command
node file.js
bun file.js
node --watch file.js
bun --watch file.js
npm test
bun test
npm pack
bun pm pack
npm publish
bun publish
npm info pkg
bun info pkg
npm outdated
bun outdated
npm audit
bun audit
npm link
bun link

Key Behavioral Differences

核心行为差异

  • No
    npm run
    prefix needed
    :
    bun run dev
    works, but so does
    bun dev
    (direct script execution)
  • --bun
    flag
    : Forces Bun runtime instead of Node.js for scripts that use
    node
    in their shebang. In
    bunfig.toml
    , set
    [run] bun = true
    to make this the default
  • Lockfile: Bun uses
    bun.lock
    (text-based, v1.2+) or
    bun.lockb
    (binary, legacy). Text lockfile is default for new projects
  • Workspace commands: Use
    --filter
    flag:
    bun --filter 'pkg-name' add dep
  • Lifecycle scripts: Bun ignores lifecycle scripts by default for security. Use
    trustedDependencies
    in package.json to allowlist packages that need postinstall etc.
  • 无需
    npm run
    前缀
    bun run dev
    可用,
    bun dev
    也可直接执行脚本
  • --bun
    标志
    :对于 shebang 中使用
    node
    的脚本,强制使用 Bun 运行时。在
    bunfig.toml
    中设置
    [run] bun = true
    可将其设为默认值
  • 锁文件:Bun 使用
    bun.lock
    (文本格式,v1.2+)或
    bun.lockb
    (二进制格式,旧版)。新项目默认使用文本锁文件
  • 工作区命令:使用
    --filter
    标志:
    bun --filter 'pkg-name' add dep
  • 生命周期脚本:出于安全考虑,Bun 默认忽略生命周期脚本。在 package.json 中使用
    trustedDependencies
    来允许需要 postinstall 等脚本的包

Package Management

包管理

Installing Dependencies

安装依赖

bash
bun install                    # Install all from package.json
bun install --frozen-lockfile  # CI mode: fail if lockfile needs update
bun install --no-save          # Install without updating package.json
bun install --production       # Skip devDependencies
bun install --dry-run          # Show what would be installed
bash
bun install                    # 从 package.json 安装所有依赖
bun install --frozen-lockfile  # CI 模式:如果锁文件需要更新则失败
bun install --no-save          # 安装但不更新 package.json
bun install --production       # 跳过 devDependencies
bun install --dry-run          # 显示将要安装的内容

Adding/Removing Packages

添加/移除包

bash
bun add pkg                    # Add to dependencies
bun add pkg@version            # Add specific version
bun add -d pkg                 # Add to devDependencies (--dev)
bun add -D pkg                 # Same as -d
bun add --optional pkg         # Add to optionalDependencies
bun add -g pkg                 # Install globally
bun add --exact pkg            # Pin exact version (no ^)
bun remove pkg                 # Remove package
bash
bun add pkg                    # 添加到 dependencies
bun add pkg@version            # 添加特定版本
bun add -d pkg                 # 添加到 devDependencies(--dev)
bun add -D pkg                 # 与 -d 效果相同
bun add --optional pkg         # 添加到 optionalDependencies
bun add -g pkg                 # 全局安装
bun add --exact pkg            # 固定精确版本(无 ^)
bun remove pkg                 # 移除包

Updating and Inspecting

更新与检查

bash
bun update                     # Update all packages
bun update pkg                 # Update specific package
bun outdated                   # Show outdated packages
bun info pkg                   # Show package metadata
bun info pkg versions          # List all available versions
bun pm ls                      # List installed packages
bun pm ls --all                # List all (including transitive)
bun pm hash                    # Print lockfile hash
bun pm cache                   # Show cache directory
bun pm cache rm                # Clear cache
bash
bun update                     # 更新所有包
bun update pkg                 # 更新特定包
bun outdated                   # 显示过时的包
bun info pkg                   # 显示包元数据
bun info pkg versions          # 列出所有可用版本
bun pm ls                      # 列出已安装的包
bun pm ls --all                # 列出所有包(包括间接依赖)
bun pm hash                    # 打印锁文件哈希值
bun pm cache                   # 显示缓存目录
bun pm cache rm                # 清除缓存

Linking and Patching

链接与补丁

bash
bun link                       # Register current package as linkable
bun link pkg-name              # Link a registered package
bun pm pack                    # Create tarball of package
bun patch pkg                  # Start patching a package
bun patch --commit pkg-dir     # Apply patch
bash
bun link                       # 将当前包注册为可链接包
bun link pkg-name              # 链接已注册的包
bun pm pack                    # 创建包的 tarball 文件
bun patch pkg                  # 开始给包打补丁
bun patch --commit pkg-dir     # 应用补丁

Publishing

发布

bash
bun publish                    # Publish to npm
bun publish --dry-run          # Preview what would be published
bun publish --tag beta         # Publish with tag
bun publish --access public    # Set access level
Reference: See
references/package-management.md
for complete flag details.
bash
bun publish                    # 发布到 npm
bun publish --dry-run          # 预览将要发布的内容
bun publish --tag beta         # 带标签发布
bun publish --access public    # 设置访问级别
参考:查看
references/package-management.md
获取完整的标志详情。

Running Scripts and Files

运行脚本与文件

Direct Execution

直接执行

bash
bun file.ts                    # Run TypeScript/JavaScript directly
bun run script-name            # Run package.json script
bun script-name                # Short form (if no conflict with bun commands)
bun --watch file.ts            # Re-run on file changes
bun --hot file.ts              # Hot reload (preserves state)
bun --env-file .env file.ts    # Load env file
bun --env-file .env.local --env-file .env file.ts  # Multiple env files
bash
bun file.ts                    # 直接运行 TypeScript/JavaScript 文件
bun run script-name            # 运行 package.json 中的脚本
bun script-name                # 简写形式(如果与 bun 命令无冲突)
bun --watch file.ts            # 文件变化时重新运行
bun --hot file.ts              # 热重载(保留状态)
bun --env-file .env file.ts    # 加载环境变量文件
bun --env-file .env.local --env-file .env file.ts  # 加载多个环境变量文件

bunx (npx Replacement)

bunx(替代 npx)

bash
bunx command                   # Run package binary (auto-installs if needed)
bunx --bun command             # Force Bun runtime for the command
bunx command@version           # Run specific version
bash
bunx command                   # 运行包的二进制文件(需要时自动安装)
bunx --bun command             # 强制使用 Bun 运行时执行命令
bunx command@version           # 运行特定版本的命令

Parallel and Sequential Execution

并行与串行执行

bash
bun --parallel run build lint typecheck    # Run all concurrently
bun --sequential run clean build deploy    # Run one after another
bash
bun --parallel run build lint typecheck    # 并发运行所有命令
bun --sequential run clean build deploy    # 按顺序逐个运行

Workspace-Aware Execution

工作区感知执行

bash
bun --filter 'pkg-name' run script    # Run in specific workspace
bun --filter '*' run script           # Run in all workspaces
bun --filter './apps/*' run build     # Run with glob pattern
bash
bun --filter 'pkg-name' run script    # 在特定工作区运行脚本
bun --filter '*' run script           # 在所有工作区运行脚本
bun --filter './apps/*' run build     # 使用 glob 匹配模式运行

Script Flags

脚本标志

bash
bun run --smol file.ts         # Reduce memory usage (sacrifice throughput)
bun run --silent script        # Suppress script name echo
bun run --shell=bun script     # Use Bun's built-in shell (cross-platform, default on Windows)
bun run --shell=system script  # Use system shell (default on macOS/Linux)
bash
bun run --smol file.ts         # 减少内存使用(牺牲吞吐量)
bun run --silent script        # 抑制脚本名称回显
bun run --shell=bun script     # 使用 Bun 内置 shell(跨平台,Windows 默认)
bun run --shell=system script  # 使用系统 shell(macOS/Linux 默认)

Zero-Config Frontend Development

零配置前端开发

Run HTML files directly as a dev server -- no Vite, Webpack, or any config needed:
bash
bun ./index.html               # Start dev server, auto-bundles JS/TS/CSS
bun --hot ./index.html         # With hot module replacement
Bun automatically transpiles TypeScript, JSX, TSX, and CSS linked from the HTML. Resolves
node_modules
imports in
<script>
tags. Enables HMR and React Fast Refresh.
Reference: See
references/running-and-execution.md
for complete details.
直接运行 HTML 文件作为开发服务器——无需 Vite、Webpack 或任何配置:
bash
bun ./index.html               # 启动开发服务器,自动打包 JS/TS/CSS
bun --hot ./index.html         # 启用热模块替换
Bun 会自动转译 HTML 中链接的 TypeScript、JSX、TSX 和 CSS。解析
<script>
标签中的
node_modules
导入。支持 HMR 和 React Fast Refresh。
参考:查看
references/running-and-execution.md
获取完整详情。

Testing

测试

Bun includes a built-in test runner compatible with Jest-like syntax.
Bun 内置了兼容 Jest 语法的测试运行器。

Running Tests

运行测试

bash
bun test                          # Run all test files
bun test file.test.ts             # Run specific file
bun test --filter "pattern"       # Filter by test name
bun test --timeout 10000         # Set timeout (ms)
bun test --bail                   # Stop on first failure
bun test --bail 5                 # Stop after 5 failures
bun test --rerun-each 3           # Run each test 3 times
bun test --only                   # Run only tests marked with .only
bun test --todo                   # Include .todo tests
bash
bun test                          # 运行所有测试文件
bun test file.test.ts             # 运行特定文件

Coverage

覆盖率

bash
bun test --coverage               # Enable code coverage
bun test --coverage-reporter text # Coverage format: text, lcov, json
bun test --coverage-dir ./cov     # Output directory
bash
bun test --coverage               # 启用代码覆盖率
bun test --coverage-reporter text # 覆盖率格式:text、lcov、json
bun test --coverage-dir ./cov     # 输出目录

Test File Patterns

测试文件模式

By default, Bun finds files matching:
*.test.{ts,tsx,js,jsx}
,
*_test.{ts,tsx,js,jsx}
,
*.spec.{ts,tsx,js,jsx}
,
*_spec.{ts,tsx,js,jsx}
, and files in
__tests__/
directories.
默认情况下,Bun 会匹配以下文件:
*.test.{ts,tsx,js,jsx}
*_test.{ts,tsx,js,jsx}
*.spec.{ts,tsx,js,jsx}
*_spec.{ts,tsx,js,jsx}
,以及
__tests__/
目录下的文件。

Snapshot Testing

快照测试

bash
bun test --update-snapshots       # Update snapshot files
bash
bun test --update-snapshots       # 更新快照文件

Watch Mode

监听模式

bash
bun test --watch                  # Re-run on file changes
Reference: See
references/testing.md
for test API, mocking, lifecycle hooks, and coverage config.
bash
bun test --watch                  # 文件变化时重新运行测试
参考:查看
references/testing.md
获取测试 API、模拟、生命周期钩子和覆盖率配置的详情。

Bundling and Compilation

打包与编译

Bundling

打包

bash
bun build ./src/index.ts --outdir ./dist           # Bundle to directory
bun build ./src/index.ts --outfile ./dist/out.js    # Bundle to single file
bun build ./src/index.ts --target browser           # Target: browser (default), bun, node
bun build ./src/index.ts --format esm               # Format: esm (default), cjs, iife
bun build ./src/index.ts --minify                   # Minify output
bun build ./src/index.ts --sourcemap external        # Sourcemaps: external, inline, linked, none
bun build ./src/index.ts --splitting                # Code splitting (ESM only)
bash
bun build ./src/index.ts --outdir ./dist           # 打包到目录
bun build ./src/index.ts --outfile ./dist/out.js    # 打包为单个文件
bun build ./src/index.ts --target browser           # 目标环境:browser(默认)、bun、node
bun build ./src/index.ts --format esm               # 格式:esm(默认)、cjs、iife
bun build ./src/index.ts --minify                   # 压缩输出

Standalone Executables

独立可执行文件

bash
bun build ./src/cli.ts --compile                    # Create self-contained executable
bun build ./src/cli.ts --compile --target bun-linux-x64    # Cross-compile
bun build ./src/cli.ts --compile --minify           # Minified executable
Available compilation targets:
bun-linux-x64
,
bun-linux-arm64
,
bun-darwin-x64
,
bun-darwin-arm64
,
bun-windows-x64
.
Browser target (v1.3.10+) -- compile to a self-contained HTML file:
bash
bun build --compile --target=browser ./app.tsx --outfile ./dist/app.html
bash
bun build ./src/cli.ts --compile                    # 创建自包含的可执行文件
bun build ./src/cli.ts --compile --target bun-linux-x64    # 交叉编译
bun build ./src/cli.ts --compile --minify           # 生成压缩后的可执行文件
可用的编译目标:
bun-linux-x64
bun-linux-arm64
bun-darwin-x64
bun-darwin-arm64
bun-windows-x64
浏览器目标(v1.3.10+)——编译为自包含的 HTML 文件:
bash
bun build --compile --target=browser ./app.tsx --outfile ./dist/app.html

Build Options

构建选项

bash
bun build ... --external pkg        # Exclude from bundle
bun build ... --define 'KEY=VALUE'  # Define compile-time constants
bun build ... --loader .ext=type    # Custom loaders (js, jsx, ts, tsx, json, css, text, file, base64, dataurl, binary)
bun build ... --entry-naming [dir]/[name].[ext]   # Output naming pattern
bun build ... --public-path /cdn/   # Public path prefix for assets
Reference: See
references/bundling-and-compilation.md
for complete options.
bash
bun build ... --external pkg        # 将包排除在打包之外
bun build ... --define 'KEY=VALUE'  # 定义编译时常量
bun build ... --loader .ext=type    # 自定义加载器(js、jsx、ts、tsx、json、css、text、file、base64、dataurl、binary)
参考:查看
references/bundling-and-compilation.md
获取完整选项。

Project Initialization

项目初始化

bash
bun init                       # Initialize new project (creates package.json, tsconfig.json, index.ts)
bun create template-name       # Create from template
bun create next-app my-app     # Example: create Next.js app
bash
bun init                       # 初始化新项目(创建 package.json、tsconfig.json、index.ts)
bun create template-name       # 从模板创建项目
bun create next-app my-app     # 示例:创建 Next.js 应用

Configuration (bunfig.toml)

配置(bunfig.toml)

Key sections:
toml
[run]
bun = true                     # Always use Bun runtime (not Node)

[install]
exact = true                   # Pin exact versions by default
peer = false                   # Don't auto-install peer deps
production = false             # Include devDeps
frozenLockfile = false         # Don't fail on lockfile mismatch
globalDir = "~/.bun/install/global"  # Global install location

[install.scopes]
"@myorg" = { token = "$NPM_TOKEN", url = "https://npm.pkg.github.com/" }

[test]
coverage = false               # Enable coverage by default
coverageReporter = ["text", "lcov"]
timeout = 5000                 # Default test timeout

[bundle]
entryPoints = ["./src/index.ts"]
outdir = "./dist"
Reference: See
references/configuration.md
for complete bunfig.toml reference.
核心配置段:
toml
[run]
bun = true                     # 始终使用 Bun 运行时(而非 Node)

[install]
exact = true                   # 默认固定精确版本
peer = false                   # 不自动安装 peer 依赖
production = false             # 包含 devDependencies
frozenLockfile = false         # 锁文件不匹配时不失败
globalDir = "~/.bun/install/global"  # 全局安装位置

[install.scopes]
"@myorg" = { token = "$NPM_TOKEN", url = "https://npm.pkg.github.com/" }

[test]
coverage = false               # 默认启用覆盖率
coverageReporter = ["text", "lcov"]
timeout = 5000                 # 默认测试超时时间

[bundle]
entryPoints = ["./src/index.ts"]
outdir = "./dist"
参考:查看
references/configuration.md
获取完整的 bunfig.toml 参考文档。

Debugging and Profiling

调试与性能分析

bash
bun --inspect file.ts              # Start debugger (WebSocket, connect via Chrome DevTools)
bun --inspect-wait file.ts         # Wait for debugger to attach before executing
bun --inspect-brk file.ts         # Break on first line
bun --cpu-prof file.ts             # Generate CPU profile
bun --cpu-prof-md file.ts          # CPU profile as Markdown (v1.3.7+)
bun --heap-prof file.ts            # Generate heap profile
bun --heap-prof-md file.ts         # Heap profile as Markdown (v1.3.7+)
BUN_JSC_logJITCodeForPerf=1 bun file.ts  # Linux perf integration
bash
bun --inspect file.ts              # 启动调试器(WebSocket,通过 Chrome DevTools 连接)
bun --inspect-wait file.ts         # 等待调试器连接后再执行
bun --inspect-brk file.ts         # 在第一行断点
bun --cpu-prof file.ts             # 生成 CPU 性能分析报告
bun --heap-prof file.ts            # 生成堆内存分析报告

Environment Variables

环境变量

bash
bun --env-file .env file.ts        # Load .env file
bun --env-file .env.local --env-file .env file.ts  # Load multiple (left takes precedence)
Bun auto-loads
.env
,
.env.production
,
.env.local
,
.env.production.local
by default based on
NODE_ENV
.
bash
bun --env-file .env file.ts        # 加载 .env 文件
bun --env-file .env.local --env-file .env file.ts  # 加载多个文件(左侧文件优先级更高)
Bun 会根据
NODE_ENV
自动加载
.env
.env.production
.env.local
.env.production.local

Built-in Features That Replace External Tools

替代外部工具的内置功能

Bun has many capabilities built in that eliminate the need for external packages or tooling:
Bun 内置了许多功能,无需依赖外部包或工具:

Native TypeScript

原生 TypeScript 支持

Bun runs
.ts
,
.tsx
files directly — no
tsc
,
ts-node
, or
tsx
needed. The transpiler is built into the runtime. Use
bun file.ts
to run any TypeScript file immediately.
Bun 可直接运行
.ts
.tsx
文件——无需
tsc
ts-node
tsx
。转译器内置在运行时中。使用
bun file.ts
即可立即运行任何 TypeScript 文件。

Workspace Catalogs

工作区目录

Bun supports
catalog:
protocol in
package.json
for centralized dependency version management across monorepo workspaces — no need for tools like
syncpack
or
manypkg
:
json
// Root package.json
{
  "workspaces": ["packages/*"],
  "catalog": {
    "react": "^19.0.0",
    "typescript": "^5.7.0"
  }
}

// packages/app/package.json
{
  "dependencies": {
    "react": "catalog:"
  }
}
Bun 在
package.json
中支持
catalog:
协议,用于在 monorepo 工作区中集中管理依赖版本——无需
syncpack
manypkg
等工具:
json
// 根目录 package.json
{
  "workspaces": ["packages/*"],
  "catalog": {
    "react": "^19.0.0",
    "typescript": "^5.7.0"
  }
}

// packages/app/package.json
{
  "dependencies": {
    "react": "catalog:"
  }
}

Built-in Test Runner

内置测试运行器

bun test
is a full Jest-compatible test runner with snapshot testing, mocking, coverage — no need for
jest
,
vitest
, or
mocha
.
bun test
是完全兼容 Jest 的测试运行器,支持快照测试、模拟、覆盖率——无需
jest
vitest
mocha

Built-in Bundler

内置打包工具

bun build
replaces
esbuild
,
webpack
,
rollup
for many use cases. Supports code splitting, tree shaking, minification, and standalone executable compilation.
bun build
在许多场景下可替代
esbuild
webpack
rollup
。支持代码分割、摇树优化、压缩和独立可执行文件编译。

Built-in SQLite

内置 SQLite

import { Database } from 'bun:sqlite'
— zero-dependency SQLite3 with prepared statements and transactions. No need for
better-sqlite3
or
sql.js
.
import { Database } from 'bun:sqlite'
——零依赖的 SQLite3,支持预处理语句和事务。无需
better-sqlite3
sql.js

Built-in Shell

内置 Shell

Bun.$
tagged template — cross-platform shell execution with automatic escaping. Replaces
execa
,
shelljs
,
zx
.
Bun.$
标签模板——跨平台的 shell 执行,自动转义。替代
execa
shelljs
zx

Built-in File I/O

内置文件 I/O

Bun.file()
and
Bun.write()
— fast file operations without importing
fs
. Auto-detects MIME types.
Bun.file()
Bun.write()
——无需导入
fs
的快速文件操作。自动检测 MIME 类型。

Built-in Glob

内置 Glob

new Bun.Glob(pattern)
— fast glob matching and file scanning. Replaces
glob
,
fast-glob
,
minimatch
.
new Bun.Glob(pattern)
——快速的 glob 匹配和文件扫描。替代
glob
fast-glob
minimatch

Built-in Password Hashing

内置密码哈希

Bun.password.hash()
and
.verify()
with bcrypt and argon2id. Replaces
bcrypt
,
argon2
packages.
Bun.password.hash()
.verify()
支持 bcrypt 和 argon2id。替代
bcrypt
argon2
包。

Built-in Compression

内置压缩

Bun.gzipSync()
,
Bun.deflateSync()
,
Bun.zstdCompressSync()
— no need for
zlib
wrapper packages.
Bun.gzipSync()
Bun.deflateSync()
Bun.zstdCompressSync()
——无需
zlib
包装器包。

Built-in Semver

内置 Semver

Bun.semver.satisfies()
,
.order()
— replaces
semver
package.
Bun.semver.satisfies()
.order()
——替代
semver
包。

Built-in Runtime APIs

内置运行时 API

For Bun's built-in runtime helpers (
Bun.s3
,
Bun.redis
,
Bun.Archive
,
JSONC
,
JSON5
,
JSONL
,
markdown
,
cron
), see the
bun-api
skill.
关于 Bun 的内置运行时助手(
Bun.s3
Bun.redis
Bun.Archive
JSONC
JSON5
JSONL
markdown
cron
),请查看
bun-api
技能。

Zero-Config Frontend Dev Server

零配置前端开发服务器

bun ./index.html
— serve HTML with auto-bundling of JS/TS/CSS, HMR, and React Fast Refresh. Replaces Vite/Webpack dev server for simple projects.
bun ./index.html
——提供 HTML 服务,自动打包 JS/TS/CSS,支持 HMR 和 React Fast Refresh。对于简单项目,可替代 Vite/Webpack 开发服务器。

ES Decorators

ES 装饰器

TC39 standard ES decorators supported natively (v1.3.10+) — no
experimentalDecorators
tsconfig needed.
原生支持 TC39 标准 ES 装饰器(v1.3.10+)——无需在 tsconfig 中设置
experimentalDecorators

Key Gotchas

关键注意事项

  1. Always use
    bun
    not
    npm
    /
    node
    /
    npx
    in Bun projects
  2. Lockfile format:
    bun.lock
    (text, v1.2+) is the default for new projects. Legacy
    bun.lockb
    is binary. Don't mix with
    package-lock.json
  3. trustedDependencies: Lifecycle scripts (postinstall, etc.) only run for packages listed in
    trustedDependencies
    in package.json
  4. --bun
    flag
    : Some tools (e.g., Next.js) use Node.js by default even when run with
    bun run
    . Use
    --bun
    or
    [run] bun = true
    in
    bunfig.toml
    to force Bun runtime
  5. Workspace protocol: Use
    "workspace:*"
    in package.json to reference workspace packages
  6. Global binaries: Installed with
    bun add -g
    , located in
    ~/.bun/bin/
  7. Node.js compatibility: Bun implements most Node.js APIs but some edge cases differ. Check https://bun.sh/docs/runtime/nodejs-apis for compatibility
  8. TypeScript: Bun runs TypeScript natively with no compilation step. Uses its own transpiler (not tsc)
  9. Auto-install: Bun can auto-install missing packages on import (disabled by default, enable with
    [install] auto = true
    in bunfig.toml)
  10. bun run
    vs
    bun
    :
    bun run script
    runs a package.json script;
    bun file.ts
    runs a file directly.
    bun script
    tries script first, then falls back to file
  1. 在 Bun 项目中始终使用
    bun
    ,而非
    npm
    /
    node
    /
    npx
  2. 锁文件格式
    bun.lock
    (文本格式,v1.2+)是新项目的默认格式。旧版
    bun.lockb
    是二进制格式。不要与
    package-lock.json
    混用
  3. trustedDependencies:生命周期脚本(如 postinstall)仅会为 package.json 中
    trustedDependencies
    列表里的包运行
  4. --bun
    标志
    :某些工具(如 Next.js)即使使用
    bun run
    运行,默认仍使用 Node.js。使用
    --bun
    或在
    bunfig.toml
    中设置
    [run] bun = true
    可强制使用 Bun 运行时
  5. 工作区协议:在 package.json 中使用
    "workspace:*"
    引用工作区包
  6. 全局二进制文件:使用
    bun add -g
    安装,位于
    ~/.bun/bin/
  7. Node.js 兼容性:Bun 实现了大多数 Node.js API,但某些边缘情况存在差异。查看 https://bun.sh/docs/runtime/nodejs-apis 了解兼容性
  8. TypeScript:Bun 原生运行 TypeScript,无需编译步骤。使用自身的转译器(而非 tsc)
  9. 自动安装:Bun 可在导入时自动安装缺失的包(默认禁用,可在 bunfig.toml 中设置
    [install] auto = true
    启用)
  10. bun run
    vs
    bun
    bun run script
    运行 package.json 中的脚本;
    bun file.ts
    直接运行文件。
    bun script
    会先尝试运行脚本,再回退到运行文件