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.jsoncompilerOptions に以下を追加します:

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 ユーザーのみ

routesfiglet を使用するように index.ts を更新します。

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 by www.bunjs.com.cn 編集