bun 快速开始

来源:Bun 教程 / 时间:2026-09-01

用 Bun.serve 构建最简 HTTP 服务器,本地运行 扩展

前提条件:已安装 Bun 并在你的 PATH 中可用。请参阅安装以进行配置。


步骤 1

使用 bun init 初始化一个新项目

bun init bun-app

bun init 会提示你选择一个模板:Blank、React 或 Library。在本指南中,请选择 Blank

bun init bun-app
✓ Select a project template: Blank

+ .gitignore
+ CLAUDE.md
+ .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
+ index.ts
+ tsconfig.json (for editor autocomplete)
+ README.md

新建的 bun-app 目录包含一个基础的 Bun 应用

步骤 2

使用 bun run 运行 index.ts

cd bun-app
bun run index.ts
Hello via Bun!

步骤 3

将 index.ts 的内容替换为以下代码

const server = Bun.serve({
  port: 3000,
  routes: {
    "/": () => new Response('Bun!'),
  }
});

console.log(`Listening on ${server.url}`);

再次运行 index.ts

bun run index.ts
Listening on https://:3000/

访问 https://:3000 来测试服务器。你应该会看到一个显示 "Bun!" 的页面

步骤 4

安装 figlet 包及其类型声明

Figlet 是一个用于将字符串转换为 ASCII 艺术字的工具

bun add figlet
bun add -d @types/figlet 
# TypeScript users only

更新 index.ts 以在 routes 中使用 figlet

import figlet from 'figlet'; 

const server = Bun.serve({
  port: 3000,
  routes: {
    "/": () => new Response('Bun!'),
    "/figlet": () => { 
      const body = figlet.textSync('Bun!'); 
      return new Response(body); 
    } 
  }
});

console.log(`Listening on ${server.url}`);

再次运行 index.ts

bun run index.ts
Listening on https://:3000/

访问 https://:3000/figlet 来测试服务器。你应该会看到一个以 ASCII 艺术字显示 "Bun!" 的页面。

____              _
| __ ) _   _ _ __ | |
|  _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)

步骤 5

现在添加一些 HTML
创建一个名为 index.html 的新文件

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Bun</title>
  </head>
  <body>
    <h1>Bun!</h1>
  </body>
</html>

然后,在 index.ts 中导入该文件并将其从根路由 / 进行响应

import figlet from 'figlet';
import index from './index.html'; 
const server = Bun.serve({
  port: 3000,
  routes: {
    "/": index, 
    "/figlet": () => {
      const body = figlet.textSync('Bun!');
      return new Response(body);
    }
  }
});

console.log(`Listening on ${server.url}`);

再次运行 index.ts

bun run index.ts
Listening on https://:3000/

访问 https://:3000 来测试服务器。你应该会看到静态 HTML 页面。

你已经使用 Bun 构建了一个 HTTP 服务器并安装了一个包。


运行脚本

Bun 也可以执行你 package.json 中的 "scripts"。添加以下 脚本

package.json

{
  "name": "my-app",
  "module": "index.ts",
  "type": "module",
  "private": true,
  "scripts": { 
    "start": "bun run index.ts" 
  }, 
  "devDependencies": {
    "@types/bun": "latest"
  },
  "peerDependencies": {
    "typescript": "^7"
  }
}

然后使用 bun run start 运行

bun run start
Listening on https://:3000/

⚡️ 性能 — bun run 比 npm run 快大约 28 倍(6毫秒比170毫秒的开销)。

上一篇: bun 安装

客服