Skip to content

概述

使用 Bun.serve 構建一個最小化的 HTTP 服務器,在本地運行它,然後通過安裝包來擴展它。

::: 前提條件:已安裝 Bun 並可在 PATH 上使用。請參閱 安裝 進行設置。 :::


使用 bun init 初始化一個新項目。

bash
bun init my-app

它會提示你選擇一個模板,可以是 BlankReactLibrary。在本指南中,我們選擇 Blank

bash
bun init my-app
bash
 選擇一個項目模板: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 文件。

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

你應該會看到控制台輸出顯示 "Hello via Bun!"

index.ts 的內容替換為以下代碼:

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

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

再次使用 bun run index.ts 運行 index.ts 文件。

bash
bun run index.ts
bash
Listening on http://localhost:3000

訪問 http://localhost:3000 測試服務器。你應該會看到一個顯示 "Bun!" 的簡單頁面。

在 Bun 上看到 TypeScript 錯誤?

如果你使用了 bun init,Bun 將自動安裝 Bun 的 TypeScript 聲明並配置你的 tsconfig.json。如果你在現有項目中嘗試 Bun,可能會在 Bun 全局對象上看到類型錯誤。

要修復此問題,首先將 @types/bun 安裝為開發依賴。

bash
bun add -d @types/bun

然後將以下內容添加到 tsconfig.json 中的 compilerOptions

json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleDetection": "force",
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "verbatimModuleSyntax": true,
    "noEmit": true
  }
}

安裝 figlet 包及其類型聲明。Figlet 是一個將字符串轉換為 ASCII 藝術的實用工具。

bash
bun add figlet
bun add -d @types/figlet # 僅限 TypeScript 用戶

更新 index.tsroutes 中使用 figlet

ts
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 文件。

bash
bun run index.ts
bash
Listening on http://localhost:3000

訪問 http://localhost:3000/figlet 測試服務器。你應該會看到一個顯示 ASCII 藝術 "Bun!" 的簡單頁面。

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

讓我們添加一些 HTML。創建一個名為 index.html 的新文件並添加以下代碼:

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 中導入此文件並從根 / 路由提供它。

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 文件。

bash
bun run index.ts
txt
Listening on http://localhost:3000

訪問 http://localhost:3000 測試服務器。你應該會看到靜態 HTML 頁面。

🎉 恭喜你!你已經使用 Bun 構建了一個簡單的 HTTP 服務器並安裝了一個包。


運行腳本

Bun 還可以執行 package.json 中的 "scripts"。添加以下腳本:

json
{
  "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 運行它。

bash
bun run start
bash
Listening on http://localhost:3000

INFO

性能bun runnpm run 快大約 28 倍(6ms 對比 170ms 的開銷)。

Bun學習網由www.bunjs.com.cn整理維護