Skip to content

개요

Bun.serve 로 최소 HTTP 서버를 구축하고, 로컬에서 실행한 다음, 패키지를 설치하여 발전시킵니다.

::: 사전 요구사항: Bun 이 설치되어 PATH 에서 사용 가능합니다. 설정은 설치 를 참조하세요. :::


bun init 으로 새 프로젝트를 초기화합니다.

bash
bun init my-app

템플릿을 선택하라는 메시지가 표시됩니다. Blank, React, Library 중 하나를 선택할 수 있습니다. 이 가이드에서는 Blank 를 선택합니다.

bash
bun init my-app
bash
 Select a project template: 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 사용자만

routes 에서 figlet 을 사용하도록 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 에서 이 파일을 import 하고 루트 / 라우트에서 제공합니다.

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 배 더 빠릅니다 (오버헤드 170ms 대비 6ms).

Bun by www.bunjs.com.cn 편집