Skip to content

Bun 快速上手

本章将引导你创建第一个 Bun 项目,了解 Bun 项目的基本结构和工作流程。

创建新项目

使用 bun init

最快的方式创建新项目:

bash
# 创建项目目录
mkdir my-bun-app
cd my-bun-app

# 初始化项目
bun init

交互式提示会询问:

package name (my-bun-app):
entry point (index.ts):

Done! A package.json file was saved in the current directory.

生成的文件结构

my-bun-app/
├── index.ts          # 入口文件
├── package.json      # 项目配置
├── tsconfig.json     # TypeScript 配置
├── README.md         # 项目说明
└── .gitignore        # Git 忽略配置

查看 package.json

json
{
  "name": "my-bun-app",
  "version": "1.0.0",
  "module": "index.ts",
  "type": "module",
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^5.0.0"
  }
}

第一个程序

Hello World

编辑 index.ts

typescript
// index.ts
const message: string = "Hello, Bun!";
console.log(message);

// 显示 Bun 版本信息
console.log(`Bun 版本: ${Bun.version}`);
console.log(`运行平台: ${process.platform}`);

运行程序:

bash
bun index.ts

输出:

Hello, Bun!
Bun 版本: 1.1.0
运行平台: darwin

使用 JavaScript

Bun 同样支持纯 JavaScript:

javascript
// app.js
const greeting = "你好,Bun!";
console.log(greeting);

// 获取当前时间
const now = new Date();
console.log(`当前时间: ${now.toLocaleString("zh-CN")}`);
bash
bun app.js

安装依赖

添加依赖包

bash
# 安装生产依赖
bun add lodash

# 安装开发依赖
bun add -d typescript @types/lodash

# 安装精确版本
bun add react@18.2.0

使用依赖

typescript
// index.ts
import _ from "lodash";

const numbers = [1, 2, 3, 4, 5];
const doubled = _.map(numbers, n => n * 2);

console.log("原数组:", numbers);
console.log("翻倍后:", doubled);
console.log("求和:", _.sum(doubled));

运行:

bash
bun index.ts
# 输出:
# 原数组: [ 1, 2, 3, 4, 5 ]
# 翻倍后: [ 2, 4, 6, 8, 10 ]
# 求和: 30

项目脚本

配置 scripts

package.json 中添加脚本:

json
{
  "name": "my-bun-app",
  "scripts": {
    "start": "bun index.ts",
    "dev": "bun --watch index.ts",
    "build": "bun build index.ts --outdir ./dist",
    "test": "bun test"
  }
}

运行脚本

bash
# 运行 start 脚本
bun run start

# 简写方式(start 可省略 run)
bun start

# 开发模式(监听文件变化)
bun run dev

# 构建项目
bun run build

创建 HTTP 服务器

Bun 内置高性能 HTTP 服务器:

typescript
// server.ts
const server = Bun.serve({
  port: 3000,
  fetch(request) {
    const url = new URL(request.url);
    
    if (url.pathname === "/") {
      return new Response("欢迎使用 Bun!");
    }
    
    if (url.pathname === "/api/hello") {
      return Response.json({ message: "Hello, World!", time: new Date() });
    }
    
    return new Response("404 Not Found", { status: 404 });
  },
});

console.log(`服务器运行在 http://localhost:${server.port}`);

运行服务器:

bash
bun server.ts

访问 http://localhost:3000 查看结果。

创建 CLI 工具

简单 CLI

typescript
// cli.ts
const args = Bun.argv;

console.log("命令行参数:", args);
console.log("脚本路径:", args[1]);
console.log("用户参数:", args.slice(2));

// 解析参数
const name = args[2] || "World";
console.log(`Hello, ${name}!`);

运行:

bash
bun cli.ts 张三
# 输出: Hello, 张三!

交互式 CLI

typescript
// interactive.ts
const prompt = "请输入你的名字: ";
process.stdout.write(prompt);

for await (const line of console) {
  console.log(`你好, ${line}!`);
  break;
}

使用环境变量

创建 .env 文件

bash
# .env
APP_NAME=我的应用
APP_PORT=3000
DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=your-secret-key

读取环境变量

typescript
// config.ts

// Bun 自动加载 .env 文件
const config = {
  appName: Bun.env.APP_NAME || "Default App",
  port: parseInt(Bun.env.APP_PORT || "3000"),
  databaseUrl: Bun.env.DATABASE_URL,
  apiKey: Bun.env.API_KEY,
};

console.log("应用配置:", config);

// 也可以使用 process.env
console.log("通过 process.env:", process.env.APP_NAME);

项目模板

React 项目

bash
bun create react my-react-app
cd my-react-app
bun dev

Next.js 项目

bash
bun create next-app my-next-app
cd my-next-app
bun dev

Elysia 项目(Bun 专用框架)

bash
bun create elysia my-api
cd my-api
bun dev

从模板创建

bash
# 从 GitHub 模板创建
bun create github-user/repo-name my-project

# 从本地模板创建
bun create ./my-template my-project

完整项目示例

创建一个简单的待办事项 API:

typescript
// todo-api.ts
interface Todo {
  id: number;
  title: string;
  completed: boolean;
}

const todos: Todo[] = [
  { id: 1, title: "学习 Bun", completed: false },
  { id: 2, title: "创建项目", completed: false },
];

const server = Bun.serve({
  port: 3000,
  
  async fetch(request) {
    const url = new URL(request.url);
    const method = request.method;
    
    // GET /api/todos - 获取所有待办
    if (method === "GET" && url.pathname === "/api/todos") {
      return Response.json(todos);
    }
    
    // POST /api/todos - 创建待办
    if (method === "POST" && url.pathname === "/api/todos") {
      const body = await request.json();
      const newTodo: Todo = {
        id: todos.length + 1,
        title: body.title,
        completed: false,
      };
      todos.push(newTodo);
      return Response.json(newTodo, { status: 201 });
    }
    
    // PUT /api/todos/:id - 更新待办
    if (method === "PUT" && url.pathname.startsWith("/api/todos/")) {
      const id = parseInt(url.pathname.split("/").pop()!);
      const todo = todos.find(t => t.id === id);
      if (todo) {
        const body = await request.json();
        Object.assign(todo, body);
        return Response.json(todo);
      }
      return Response.json({ error: "未找到" }, { status: 404 });
    }
    
    return Response.json({ error: "未找到" }, { status: 404 });
  },
});

console.log(`待办事项 API 运行在 http://localhost:${server.port}`);

测试 API:

bash
# 获取所有待办
curl http://localhost:3000/api/todos

# 创建新待办
curl -X POST http://localhost:3000/api/todos \
  -H "Content-Type: application/json" \
  -d '{"title": "新任务"}'

# 更新待办
curl -X PUT http://localhost:3000/api/todos/1 \
  -H "Content-Type: application/json" \
  -d '{"completed": true}'

小结

本章介绍了:

  • ✅ 使用 bun init 创建项目
  • ✅ 运行 TypeScript/JavaScript 文件
  • ✅ 安装和使用依赖包
  • ✅ 配置和运行项目脚本
  • ✅ 创建 HTTP 服务器
  • ✅ 使用环境变量
  • ✅ 使用项目模板

下一步

继续阅读 运行脚本 深入了解 Bun 的脚本运行机制。

本站内容仅供学习和研究使用。