概述
使用 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 的開銷)。