Bun Quick Start
This chapter will guide you through creating your first Bun project and understanding the basic structure and workflow of Bun projects.
Creating a New Project
Using bun init
The fastest way to create a new project:
bash
# Create project directory
mkdir my-bun-app
cd my-bun-app
# Initialize project
bun initInteractive prompts will ask:
package name (my-bun-app):
entry point (index.ts):
Done! A package.json file was saved in the current directory.Generated File Structure
my-bun-app/
├── index.ts # Entry file
├── package.json # Project configuration
├── tsconfig.json # TypeScript configuration
├── README.md # Project documentation
└── .gitignore # Git ignore configurationViewing package.json
json
{
"name": "my-bun-app",
"version": "1.0.0",
"module": "index.ts",
"type": "module",
"devDependencies": {
"@types/bun": "latest"
},
"peerDependencies": {
"typescript": "^5.0.0"
}
}Your First Program
Hello World
Edit index.ts:
typescript
// index.ts
const message: string = "Hello, Bun!";
console.log(message);
// Display Bun version info
console.log(`Bun version: ${Bun.version}`);
console.log(`Runtime platform: ${process.platform}`);Run the program:
bash
bun index.tsOutput:
Hello, Bun!
Bun version: 1.1.0
Runtime platform: darwinUsing JavaScript
Bun also supports pure JavaScript:
javascript
// app.js
const greeting = "Hello, Bun!";
console.log(greeting);
// Get current time
const now = new Date();
console.log(`Current time: ${now.toLocaleString("en-US")}`);bash
bun app.jsInstalling Dependencies
Adding Packages
bash
# Install production dependencies
bun add lodash
# Install dev dependencies
bun add -d typescript @types/lodash
# Install exact version
bun add react@18.2.0Using Dependencies
typescript
// index.ts
import _ from "lodash";
const numbers = [1, 2, 3, 4, 5];
const doubled = _.map(numbers, n => n * 2);
console.log("Original array:", numbers);
console.log("Doubled:", doubled);
console.log("Sum:", _.sum(doubled));Run:
bash
bun index.ts
# Output:
# Original array: [ 1, 2, 3, 4, 5 ]
# Doubled: [ 2, 4, 6, 8, 10 ]
# Sum: 30Project Scripts
Configuring Scripts
Add scripts in package.json:
json
{
"name": "my-bun-app",
"scripts": {
"start": "bun index.ts",
"dev": "bun --watch index.ts",
"build": "bun build index.ts --outdir ./dist",
"test": "bun test"
}
}Running Scripts
bash
# Run start script
bun run start
# Shorthand (start can omit run)
bun start
# Development mode (watch for file changes)
bun run dev
# Build project
bun run buildCreating an HTTP Server
Bun has a built-in high-performance HTTP server:
typescript
// server.ts
const server = Bun.serve({
port: 3000,
fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return new Response("Welcome to Bun!");
}
if (url.pathname === "/api/hello") {
return Response.json({ message: "Hello, World!", time: new Date() });
}
return new Response("404 Not Found", { status: 404 });
},
});
console.log(`Server running at http://localhost:${server.port}`);Run the server:
bash
bun server.tsVisit http://localhost:3000 to see the result.
Creating CLI Tools
Simple CLI
typescript
// cli.ts
const args = Bun.argv;
console.log("Command line arguments:", args);
console.log("Script path:", args[1]);
console.log("User arguments:", args.slice(2));
// Parse arguments
const name = args[2] || "World";
console.log(`Hello, ${name}!`);Run:
bash
bun cli.ts John
# Output: Hello, John!Interactive CLI
typescript
// interactive.ts
const prompt = "Please enter your name: ";
process.stdout.write(prompt);
for await (const line of console) {
console.log(`Hello, ${line}!`);
break;
}Using Environment Variables
Creating .env File
bash
# .env
APP_NAME=My App
APP_PORT=3000
DATABASE_URL=postgresql://localhost:5432/mydb
API_KEY=your-secret-keyReading Environment Variables
typescript
// config.ts
// Bun automatically loads .env file
const config = {
appName: Bun.env.APP_NAME || "Default App",
port: parseInt(Bun.env.APP_PORT || "3000"),
databaseUrl: Bun.env.DATABASE_URL,
apiKey: Bun.env.API_KEY,
};
console.log("App config:", config);
// You can also use process.env
console.log("Through process.env:", process.env.APP_NAME);Project Templates
React Project
bash
bun create react my-react-app
cd my-react-app
bun devNext.js Project
bash
bun create next-app my-next-app
cd my-next-app
bun devElysia Project (Bun-specific Framework)
bash
bun create elysia my-api
cd my-api
bun devCreating from Template
bash
# Create from GitHub template
bun create github-user/repo-name my-project
# Create from local template
bun create ./my-template my-projectComplete Project Example
Create a simple todo API:
typescript
// todo-api.ts
interface Todo {
id: number;
title: string;
completed: boolean;
}
const todos: Todo[] = [
{ id: 1, title: "Learn Bun", completed: false },
{ id: 2, title: "Create project", completed: false },
];
const server = Bun.serve({
port: 3000,
async fetch(request) {
const url = new URL(request.url);
const method = request.method;
// GET /api/todos - Get all todos
if (method === "GET" && url.pathname === "/api/todos") {
return Response.json(todos);
}
// POST /api/todos - Create todo
if (method === "POST" && url.pathname === "/api/todos") {
const body = await request.json();
const newTodo: Todo = {
id: todos.length + 1,
title: body.title,
completed: false,
};
todos.push(newTodo);
return Response.json(newTodo, { status: 201 });
}
// PUT /api/todos/:id - Update todo
if (method === "PUT" && url.pathname.startsWith("/api/todos/")) {
const id = parseInt(url.pathname.split("/").pop()!);
const todo = todos.find(t => t.id === id);
if (todo) {
const body = await request.json();
Object.assign(todo, body);
return Response.json(todo);
}
return Response.json({ error: "Not found" }, { status: 404 });
}
return Response.json({ error: "Not found" }, { status: 404 });
},
});
console.log(`Todo API running at http://localhost:${server.port}`);Test the API:
bash
# Get all todos
curl http://localhost:3000/api/todos
# Create new todo
curl -X POST http://localhost:3000/api/todos \
-H "Content-Type: application/json" \
-d '{"title": "New task"}'
# Update todo
curl -X PUT http://localhost:3000/api/todos/1 \
-H "Content-Type: application/json" \
-d '{"completed": true}'Summary
This chapter introduced:
- ✅ Using
bun initto create projects - ✅ Running TypeScript/JavaScript files
- ✅ Installing and using dependencies
- ✅ Configuring and running project scripts
- ✅ Creating HTTP servers
- ✅ Using environment variables
- ✅ Using project templates
Next Steps
Continue reading Running Scripts to learn more about Bun's script execution mechanism.