Contents
see List개요
Bun은 JavaScriptCore 엔진을 기반으로 한 초고속 JavaScript 런타임입니다. Node.js와 호환되면서도 3배 이상 빠른 성능을 제공하며, 빌트인 번들러, 테스트 러너, 패키지 매니저를 포함합니다.
Bun의 핵심 특징
- 압도적인 속도: JavaScriptCore 엔진과 Zig로 작성된 네이티브 코드로 Node.js 대비 3-4배 빠릅니다.
- 올인원 도구: 런타임, 패키지 매니저, 번들러, 테스트 러너가 통합되어 있습니다.
- Node.js 호환성: 대부분의 Node.js API와 npm 패키지를 그대로 사용할 수 있습니다.
- TypeScript 네이티브 지원: 별도 설정 없이 .ts 파일을 바로 실행할 수 있습니다.
설치 및 기본 사용법
# macOS/Linux
curl -fsSL https://bun.sh/install | bash
# Windows (WSL2 권장)
powershell -c "irm bun.sh/install.ps1 | iex"
# 버전 확인
bun --version
# TypeScript 파일 직접 실행
bun run index.ts
# 프로젝트 초기화
bun init
# 의존성 설치
bun install
# 스크립트 실행
bun run dev
빌트인 API 활용
1. 초고속 HTTP 서버
Bun의 HTTP 서버는 Express보다 5배 이상 빠릅니다:
// server.ts
const server = Bun.serve({
port: 3000,
fetch(req) {
const url = new URL(req.url);
if (url.pathname === '/') {
return new Response('Hello, Bun!');
}
if (url.pathname === '/json') {
return Response.json({ message: 'Fast JSON response' });
}
if (url.pathname === '/user') {
const user = {
id: 1,
name: 'John Doe',
email: 'john@example.com',
};
return Response.json(user);
}
return new Response('Not Found', { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);
2. WebSocket 지원
// websocket-server.ts
const server = Bun.serve({
port: 3001,
fetch(req, server) {
if (server.upgrade(req)) {
return; // 웹소켓으로 업그레이드됨
}
return new Response('Upgrade to WebSocket required');
},
websocket: {
open(ws) {
console.log('Client connected');
ws.subscribe('chat-room');
},
message(ws, message) {
console.log(`Received: ${message}`);
// 같은 룸의 모든 클라이언트에게 브로드캐스트
server.publish('chat-room', message);
},
close(ws) {
console.log('Client disconnected');
},
},
});
3. 파일 I/O
Bun은 네이티브 파일 API를 제공하여 Node.js보다 훨씬 빠릅니다:
// 파일 읽기 (자동으로 UTF-8 디코딩)
const file = Bun.file('package.json');
const text = await file.text();
const json = await file.json();
// 파일 쓰기
await Bun.write('output.txt', 'Hello, World!');
await Bun.write('data.json', { name: 'Bun', version: '1.0' });
// 스트림 처리
const response = await fetch('https://example.com/large-file.zip');
await Bun.write('download.zip', response);
// Glob 패턴으로 파일 찾기
const glob = new Bun.Glob('**/*.ts');
for await (const file of glob.scan('.')) {
console.log(file);
}
패키지 매니저로서의 Bun
Bun은 npm, yarn, pnpm보다 훨씬 빠른 패키지 설치 속도를 자랑합니다:
# 패키지 설치
bun add react react-dom
bun add -d typescript @types/react
# 패키지 제거
bun remove lodash
# 전역 설치
bun add -g typescript
# package.json 기반 설치 (node_modules 생성)
bun install
# 캐시 사용 안 함
bun install --no-cache
# Lockfile 업데이트
bun install --force
빌트인 번들러
별도 설정 없이 TypeScript, JSX를 번들링할 수 있습니다:
// build.ts
await Bun.build({
entrypoints: ['./src/index.tsx'],
outdir: './dist',
minify: true,
sourcemap: 'external',
target: 'browser',
splitting: true, // 코드 스플리팅
external: ['react', 'react-dom'], // 번들에서 제외
});
console.log('Build complete!');
# 빌드 실행
bun run build.ts
# 또는 CLI로 직접 빌드
bun build ./src/index.tsx --outdir ./dist --minify
빌트인 테스트 러너
Jest와 유사한 API로 매우 빠른 테스트를 실행할 수 있습니다:
// math.test.ts
import { expect, test, describe } from 'bun:test';
describe('Math operations', () => {
test('addition', () => {
expect(2 + 2).toBe(4);
});
test('subtraction', () => {
expect(5 - 3).toBe(2);
});
test('async operation', async () => {
const result = await Promise.resolve(42);
expect(result).toBe(42);
});
});
// API 테스트
describe('HTTP Server', () => {
test('GET /', async () => {
const response = await fetch('http://localhost:3000/');
expect(response.status).toBe(200);
expect(await response.text()).toBe('Hello, Bun!');
});
});
# 테스트 실행
bun test
# watch 모드
bun test --watch
# 커버리지
bun test --coverage
환경 변수 관리
Bun은 자동으로 .env 파일을 로드합니다:
# .env
DATABASE_URL=postgresql://localhost/mydb
API_KEY=secret-key-123
// app.ts
console.log(process.env.DATABASE_URL);
// dotenv 패키지 불필요!
// Bun.env로도 접근 가능
console.log(Bun.env.API_KEY);
Node.js에서 Bun으로 마이그레이션
// package.json 수정
{
"scripts": {
"dev": "bun run src/index.ts",
"build": "bun build src/index.ts --outdir dist",
"start": "bun run dist/index.js",
"test": "bun test"
}
}
# 기존 node_modules 제거
rm -rf node_modules package-lock.json
# Bun으로 재설치
bun install
# 실행
bun run dev
활용 팁
- 프로덕션 환경에서는 안정성을 위해 충분한 테스트를 거친 후 도입하세요.
- Bun.serve()를 활용하여 고성능 API 서버를 구축하세요.
- 빌트인 번들러로 webpack/vite 설정의 복잡성을 제거하세요.
- 테스트 러너로 빠른 피드백 루프를 구축하세요.
- Node.js 네이티브 모듈이 필요한 경우 호환성을 미리 확인하세요.
마무리
Bun은 JavaScript 생태계의 게임 체인저입니다. 빠른 속도와 간결한 API로 개발 경험을 크게 향상시킬 수 있으며, 특히 새로운 프로젝트에서는 Node.js 대신 Bun을 적극 고려해볼 만합니다.