概述
使用 Bun.serve 构建一个最小化的 HTTP 服务器,在本地运行它,然后通过安装包来扩展它。
::: 前提条件:已安装 Bun 并可在 PATH 上使用。请参阅 安装 进行设置。 :::
使用 bun init 初始化一个新项目。
bun init my-app它会提示你选择一个模板,可以是 Blank、React 或 Library。在本指南中,我们选择 Blank。
bun init my-app✓ 选择一个项目模板:Blank
- .gitignore
- CLAUDE.md
- .cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc -> CLAUDE.md
- index.ts
- tsconfig.json(用于编辑器自动完成)
- README.md这会自动创建一个带有基本 Bun 应用的 my-app 目录。
使用 bun run index.ts 运行 index.ts 文件。
cd my-app
bun run index.tsHello via Bun!你应该会看到控制台输出显示 "Hello via Bun!"。
将 index.ts 的内容替换为以下代码:
const server = Bun.serve({
port: 3000,
routes: {
"/": () => new Response('Bun!'),
}
});
console.log(`Listening on ${server.url}`);再次使用 bun run index.ts 运行 index.ts 文件。
bun run index.tsListening on http://localhost:3000访问 http://localhost:3000 测试服务器。你应该会看到一个显示 "Bun!" 的简单页面。
在 Bun 上看到 TypeScript 错误?
如果你使用了 bun init,Bun 将自动安装 Bun 的 TypeScript 声明并配置你的 tsconfig.json。如果你在现有项目中尝试 Bun,可能会在 Bun 全局对象上看到类型错误。
要修复此问题,首先将 @types/bun 安装为开发依赖。
bun add -d @types/bun然后将以下内容添加到 tsconfig.json 中的 compilerOptions:
{
"compilerOptions": {
"lib": ["ESNext"],
"target": "ESNext",
"module": "Preserve",
"moduleDetection": "force",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true
}
}安装 figlet 包及其类型声明。Figlet 是一个将字符串转换为 ASCII 艺术的实用工具。
bun add figlet
bun add -d @types/figlet # 仅限 TypeScript 用户更新 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);
}
}
});再次使用 bun run index.ts 运行 index.ts 文件。
bun run index.tsListening on http://localhost:3000访问 http://localhost:3000/figlet 测试服务器。你应该会看到一个显示 ASCII 艺术 "Bun!" 的简单页面。
____ _
| __ ) _ _ _ __ | |
| _ \| | | | '_ \| |
| |_) | |_| | | | |_|
|____/ \__,_|_| |_(_)让我们添加一些 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}`);再次使用 bun run index.ts 运行 index.ts 文件。
bun run index.tsListening on http://localhost:3000访问 http://localhost:3000 测试服务器。你应该会看到静态 HTML 页面。
🎉 恭喜你!你已经使用 Bun 构建了一个简单的 HTTP 服务器并安装了一个包。
运行脚本
Bun 还可以执行 package.json 中的 "scripts"。添加以下脚本:
{
"name": "quickstart",
"module": "index.ts",
"type": "module",
"private": true,
"scripts": {
"start": "bun run index.ts"
},
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5"
}
}然后使用 bun run start 运行它。
bun run startListening on http://localhost:3000INFO
性能 — bun run 比 npm run 快大约 28 倍(6ms 对比 170ms 的开销)。