# 📋 Шпаргалка по встроенным возможностям Bun
## ⚡ Быстрые примеры
### 1️⃣ HTML рендер (Template Literals)
```typescript
const html = `
${title}
${content}
`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
**Скорость:** 0.1ms | **Когда:** 80% случаев
---
### 2️⃣ JSON API
```typescript
const data = { status: "ok", items: [] };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
```
**Встроено:** V8 оптимизация | **Когда:** API endpoints
---
### 3️⃣ Статические файлы
```typescript
return new Response(Bun.file("static/style.css"));
```
**Скорость:** 0.05ms | **Когда:** CSS, JS, медиа
---
### 4️⃣ Динамический контент
```typescript
const items = ["A", "B", "C"];
const html = `
${items.map(i => `- ${i}
`).join("")}
`;
```
**Когда:** Списки, таблицы
---
### 5️⃣ React компонент (SSR)
```typescript
import React from "react";
const Page = ({ title }) => (
{title}
);
const html = React.renderToString();
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
**Скорость:** 2-5ms | **Когда:** 15% случаев
---
### 6️⃣ Streaming большого файла
```typescript
return new Response(Bun.file("large-file.zip"));
// или
const readable = new ReadableStream({ /* ... */ });
return new Response(readable);
```
**Скорость:** 0.05ms | **Когда:** Большие файлы
---
### 7️⃣ Кеширование
```typescript
return new Response(html, {
headers: {
"Cache-Control": "public, max-age=3600",
"ETag": '"123456"'
}
});
```
**Когда:** Статические ассеты
---
### 8️⃣ Cookie
```typescript
// Установка
return new Response(html, {
headers: {
"Set-Cookie": "session=abc123; Path=/; HttpOnly"
}
});
// Чтение
const cookie = req.headers.get("cookie");
```
---
### 9️⃣ TypeScript (встроенный)
```typescript
const greeting: string = "Hello";
const numbers: number[] = [1, 2, 3];
interface User { name: string; age: number; }
```
**Компиляция:** встроенная | **Конфигурация:** опциональна
---
### 🔟 Web Standards API
```typescript
const req = new Request("http://example.com");
const res = new Response("content");
const headers = new Headers({ "Content-Type": "text/html" });
const url = new URL("https://example.com");
const params = new URLSearchParams("a=1");
const blob = new Blob(["data"]);
```
---
## 🎯 Таблица выбора
```
Нужно что делать? Используйте это
─────────────────────────────────────────────────────
HTML страница Template Literals
API endpoint (JSON) JSON.stringify
Статический файл Bun.file()
Большой файл Streaming API
React компонент React.renderToString
Переиспользуемая логика Custom функция
Типизация TypeScript
Кеширование браузером Cache-Control
Сохранить состояние Cookie
```
---
## 📊 Производительность
```
Template Literals 0.1ms ⚡⚡⚡ ИСПОЛЬЗУЙТЕ
Bun.file() 0.05ms ⚡⚡⚡ ДЛЯ ФАЙЛОВ
Streaming 0.05ms ⚡⚡⚡ БОЛЬШИЕ
JSON.stringify() встроено ⚡⚡⚡ ОПТИМИЗИРОВАН
React SSR 2-5ms ⚡ КОГДА НУЖНЫ
```
---
## 🚀 Структура сервера
```typescript
// 1. Импорты
import { Server } from "./server";
import { Router } from "./router";
// 2. Создание сервера
const server = new Server({ port: 3000 });
const router = server.getRouter();
// 3. Регистрация маршрутов
router.get("/", async (req, url) => {
const html = `...`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
});
router.get("/api/data", async (req, url) => {
const data = { status: "ok" };
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
});
// 4. Запуск
server.start();
```
---
## 🎓 Правила для начинающих
1. **Template Literals в 80% случаев**
```typescript
const html = `${title}
`;
```
2. **JSON.stringify для API**
```typescript
return new Response(JSON.stringify(data));
```
3. **Bun.file для статики**
```typescript
return new Response(Bun.file("static/style.css"));
```
4. **React только когда нужны компоненты**
```typescript
// NOT в 80% случаев - используйте Template Literals!
```
5. **TypeScript для типизации**
```typescript
function handler(req: Request): Response { }
```
---
## 📦 Не требует установки
```
❌ НЕ нужно устанавливать:
- HTML рендер библиотеку
- Шаблонизатор
- HTTP сервер
- TypeScript компилятор
- JSON библиотеку
✅ ВСЕ встроено в Bun!
```
---
## 💡 Советы производительности
1. **Кешируйте статику**
```typescript
"Cache-Control": "public, max-age=86400"
```
2. **Используйте Streaming для больших файлов**
```typescript
return new Response(Bun.file("huge-file.zip"));
```
3. **Делайте Template Literals чистыми**
```typescript
// ХОРОШО
const html = `${htmlEscape(title)}
`;
// ПЛОХО
const html = "" + title + "
";
```
4. **Минифицируйте JSON если нужно**
```typescript
JSON.stringify(data) // Компактный
// vs
JSON.stringify(data, null, 2) // С отступами (для debug)
```
5. **Используйте ETag для кеширования**
```typescript
"ETag": '"hash-of-content"'
```
---
## 🔗 Документация в проекте
- **WHAT_BUN_CAN_DO.md** - Главный файл (начните отсюда!)
- **BUN_CAPABILITIES.md** - 10 возможностей
- **BUN_RENDERING.md** - Подробное руководство
- **README.md** - Полная документация
- **DOCS_INDEX.md** - Индекс всего
---
## 🎉 Итого
**Bun имеет всё что нужно для веб-разработки БЕЗ дополнительных библиотек!**
Используйте эту шпаргалку как быструю справку.
Для деталей смотрите основные файлы документации.
Happy Bun coding! 🚀