📥 安装 Bun
macOS / Linux / WSL
bash
curl -fsSL https://bun.sh/install | bash
# 重新加载 shell
source ~/.bashrc # 或 ~/.zshrc
Windows (PowerShell)
powershell
powershell -c "irm bun.sh/install.ps1 | iex"
其他方式
bash
# Homebrew (macOS)
brew install bun
# npm
npm install -g bun
# Docker
docker run --rm oven/bun bun --version
🚀 第一个项目
初始化项目
bash
# 创建新项目
bun init my-app
cd my-app
# 或在现有目录初始化
bun init
Hello World
typescript
// index.ts
console.log("Hello, Bun!");
// HTTP 服务器
Bun.serve({
port: 3000,
fetch(req) {
return new Response("Hello, World!");
},
});
console.log("Server running at http://localhost:3000");
bash
# 运行
bun run index.ts
# 或热重载
bun --hot run index.ts
📦 包管理
bash
# 安装所有依赖
bun install
# 添加依赖
bun add react react-dom
bun add -d typescript @types/react
# 移除依赖
bun remove react
# 更新依赖
bun update
# 运行脚本
bun run dev
bun run build
🔄 从 Node.js 迁移
直接替换
bash
# Node.js 项目可直接使用 Bun
bun install # 使用 bun.lockb 替代 package-lock.json
bun run server.js # 运行 Node.js 代码
# 替换命令
node server.js → bun run server.js
npm install → bun install
npm run dev → bun run dev
npx → bunx
兼容性检查
✅ 高兼容性
- fs, path, http, crypto 等核心模块
- Buffer, process, console 等全局对象
- npm 包自动安装
- package.json 脚本支持
🔧 常用命令速查
| 命令 | 说明 |
|---|---|
bun run file.ts | 运行 TypeScript/JavaScript |
bun install | 安装依赖 |
bun add pkg | 添加依赖 |
bun test | 运行测试 |
bun build | 打包项目 |
bunx | 运行 npm 包(类似 npx) |
bun upgrade | 升级 Bun |