執行環境套件管理器打包器測試執行器程式碼檢查格式化指南參考部落格意見回饋

快速開始

使用 Bun 建置您的第一個應用

概覽

使用 Bun.serve 建置一個簡約的 HTTP 伺服器,在本地執行它,然後通過安裝一個包來擴充套件它。


  1. 步驟 1

    使用 bun init 初始化一個新專案。

    terminal
    bun init my-app
    

    bun init 會提示您選擇一個模板:Blank、React 或 Library。對於本指南,請選擇 Blank。

    terminal
    bun init my-app
    
    Text
    ✓ 選擇一個專案模板: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
    

    新的 my-app 目錄包含一個基本的 Bun 應用。

  2. 步驟 2

    使用 bun run 執行 index.ts。

    terminal
    cd my-app
    bun run index.ts
    
    Text
    Hello via Bun!
    
  3. 步驟 3

    將 index.ts 的內容替換為以下程式碼:

    index.ts
    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": () => new Response('Bun!'),
      }
    });
    
    console.log(`Listening on ${server.url}`);
    

    再次執行 index.ts。

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

    訪問 http://localhost:3000 測試伺服器。您應該看到一個顯示 "Bun!" 的頁面。

    在 Bun 中看到 TypeScript 錯誤?

    bun init 會安裝 Bun 的 TypeScript 宣告並設定您的 tsconfig.json。如果您正在現有專案中嘗試使用 Bun,可能會在 Bun 全域性變數上看到型別錯誤。

    要解決此問題,首先安裝 @types/bun 作為開發相依。

    terminal
    bun add -d @types/bun
    

    然後在 tsconfig.json 的 compilerOptions 中新增以下設定:

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

    安裝 figlet 包及其型別宣告。Figlet 是一個將字串轉換為 ASCII 藝術的工具。

    terminal
    bun add figlet
    bun add -d @types/figlet # 僅限 TypeScript 使用者
    

    更新 index.ts,在 routes 中使用 figlet。

    index.ts
    import figlet from 'figlet'; // [!code ++]
    
    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": () => new Response('Bun!'),
        "/figlet": () => { // [!code ++]
          const body = figlet.textSync('Bun!'); // [!code ++]
          return new Response(body); // [!code ++]
        } // [!code ++]
      }
    });
    
    console.log(`Listening on ${server.url}`);
    

    再次執行 index.ts。

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

    訪問 http://localhost:3000/figlet 測試伺服器。您應該看到以 ASCII 藝術形式顯示的 "Bun!"。

    Text
    ____              _
    | __ ) _   _ _ __ | |
    |  _ \| | | | '_ \| |
    | |_) | |_| | | | |_|
    |____/ \__,_|_| |_(_)
    
  5. 步驟 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 中匯入此檔案,並從根路由 / 提供它。

    index.ts
    import figlet from 'figlet';
    import index from './index.html'; // [!code ++]
    
    const server = Bun.serve({
      port: 3000,
      routes: {
        "/": index, // [!code ++]
        "/figlet": () => {
          const body = figlet.textSync('Bun!');
          return new Response(body);
        }
      }
    });
    
    console.log(`Listening on ${server.url}`);
    

    再次執行 index.ts。

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

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

您已經使用 Bun 建置了一個 HTTP 伺服器並安裝了一個包。


執行指令碼

Bun 也可以執行 package.json 中的 "scripts"。新增以下指令碼:

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

然後通過 bun run start 執行它。

terminal
bun run start
Text
Listening on http://localhost:3000/