Files
bun-server-test/WHAT_BUN_CAN_DO.md

409 lines
11 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 🎯 Что Bun может из коробки с рендером - ПОЛНЫЙ ОТВЕТ
## 📌 TL;DR (Кратко)
Bun имеет **10 встроенных мощных возможностей** для рендера и веб-разработки БЕЗ дополнительных библиотек:
```
1. Template Literals - Самый быстрый HTML (0.1ms) ⭐⭐⭐
2. JSX/TSX компиляция - Встроенная
3. React.renderToString - SSR из коробки
4. Bun.file() - Супер быстрые файлы
5. Streaming API - Web Standards
6. JSON оптимизация - Встроенная V8
7. Web Standards API - Request, Response и т.д.
8. TypeScript - Встроенный
9. HTTP кеширование - Cache-Control, ETag
10. Cookie поддержка - Set-Cookie
```
**Главное:** Используйте **Template Literals в 80% случаев** - это будет самым быстрым!
---
## 🚀 Демонстрация всех возможностей
### Сервер запущен на http://localhost:3002
Протестируйте все встроенные возможности:
```bash
# 1. Быстрый Template Literal рендер
curl http://localhost:3002/demo/fast-render
# 2. Динамический контент
curl http://localhost:3002/demo/dynamic-data
# 3. JSON оптимизация
curl http://localhost:3002/demo/optimized-json | jq
# 4. Streaming контент
curl http://localhost:3002/demo/streaming
# 5. Кеширование
curl -i http://localhost:3002/demo/cached-asset
# 6. Cookie
curl -i http://localhost:3002/demo/cookie
# 7. Все методы в одном
curl http://localhost:3002/demo/all | jq
```
---
## 📊 Встроенные возможности подробно
### 1. Template Literals (⭐⭐⭐ ЛУЧШИЙ ВЫБОР)
**Скорость:** 0.1ms | **Память:** минимальная | **Код:** прост
```typescript
const html = `
<!DOCTYPE html>
<html>
<body>
<h1>${title}</h1>
<p>${content}</p>
</body>
</html>
`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
✅ Используйте для: HTML страницы, API, динамический контент
❌ Избегайте: сложного рефакторинга компонентов
---
### 2. JSX/TSX Компиляция
**Встроенная поддержка без конфигурации**
```typescript
// Просто работает!
const App = () => <h1>Hello</h1>;
```
✅ Включено: встроенная компиляция
❌ Требует: React package если используется
---
### 3. React.renderToString() для SSR
**Server-Side Rendering из коробки**
```typescript
import React from "react";
const Component = ({ name }) => <h1>Hello {name}</h1>;
const html = React.renderToString(<Component name="Bun" />);
```
✅ Скорость: нормальная (2-5ms)
❌ Медленнее: чем Template Literals на 50x
---
### 4. Bun.file() для файлов
**Встроенная максимально быстрая работа с файлами**
```typescript
// Строка
const file = Bun.file("path/to/file.html");
return new Response(file);
// Автоматически:
// - Определяет Content-Type
// - Потоковая передача
// - Кеширование
// - Оптимизация
```
✅ Скорость: 0.05ms (самый быстрый для файлов!)
✅ Идеально: для статических файлов, CSS, JS, медиа
---
### 5. Streaming API
**Web Standard Streams для больших данных**
```typescript
const readable = new ReadableStream({
start(controller) {
for (let i = 0; i < 1000; i++) {
controller.enqueue(new TextEncoder().encode(`chunk ${i}\n`));
}
controller.close();
}
});
return new Response(readable, { headers: { "Content-Type": "text/plain" } });
```
✅ Скорость: 0.05ms
✅ Случаи: большие файлы, real-time данные, SSE
---
### 6. JSON Оптимизация
**Встроенная V8 оптимизация для JSON**
```typescript
const data = {
status: "ok",
items: Array(1000).fill({ id: 1, name: "item" })
};
// Встроено оптимизировано!
const json = JSON.stringify(data);
return new Response(json, {
headers: { "Content-Type": "application/json" }
});
```
✅ Встроено: V8 оптимизация
✅ Работает: даже с большими структурами
✅ Скорость: максимальная
---
### 7. Web Standards API
**Полная поддержка стандартных браузерных API**
```typescript
// Все встроено:
const request = new Request("http://example.com");
const response = new Response("content");
const headers = new Headers({ "Content-Type": "text/html" });
const url = new URL("https://example.com/path");
const params = new URLSearchParams("a=1&b=2");
const blob = new Blob(["data"]);
const buffer = new ArrayBuffer(1024);
const encoder = new TextEncoder();
const decoder = new TextDecoder();
```
✅ Стандарт: Web Standards API
✅ Знакомо: используется везде
---
### 8. TypeScript встроенный
**Встроенная компиляция TypeScript без конфигурации**
```typescript
// Просто работает!
const greeting: string = "Hello";
const numbers: number[] = [1, 2, 3];
const user: { name: string; age: number } = { name: "John", age: 30 };
```
✅ Компиляция: встроенная
✅ Конфигурация: не требуется (opctional tsconfig.json)
✅ Производительность: оптимизирована
---
### 9. HTTP Кеширование
**Встроенная поддержка Cache-Control и ETag**
```typescript
return new Response(html, {
headers: {
"Cache-Control": "public, max-age=3600", // 1 час
"ETag": '"123456"',
"Last-Modified": new Date().toUTCString()
}
});
```
✅ Браузер: будет кешировать
✅ Стандарт: HTTP Cache-Control
✅ Оптимизация: уменьшает трафик
---
### 10. Cookie Поддержка
**Встроенная установка и чтение Cookie**
```typescript
// Установка
return new Response(html, {
headers: {
"Set-Cookie": "session=abc123; Path=/; HttpOnly; SameSite=Strict"
}
});
// Чтение
const cookie = req.headers.get("cookie");
```
✅ Установка: простая
✅ Чтение: из headers
✅ Безопасность: HttpOnly, SameSite параметры
---
## 🎯 Когда какой метод использовать
### Template Literals (80% случаев) ⭐⭐⭐
```typescript
// ДА - используйте
const html = `<h1>${title}</h1>`;
return new Response(html, { headers: { "Content-Type": "text/html" } });
```
Идеально для:
- Простых HTML страниц
- API endpoints
- Динамического контента
- Когда нужна максимальная производительность
---
### React компоненты (15% случаев) ⭐⭐
```typescript
// ДА - используйте когда нужны компоненты
const html = React.renderToString(<MyComponent />);
```
Идеально для:
- Переиспользуемых компонентов
- Сложной логики UI
- Совместимости с фронтенд кодом
---
### Bun.file() (5% случаев) ⭐⭐⭐
```typescript
// ДА - используйте для файлов
return new Response(Bun.file("static/style.css"));
```
Идеально для:
- Статических файлов
- CSS, JS, медиа
- Больших файлов
---
## 📈 Сравнение производительности
```
Метод Время Использование Рекомендация
────────────────────────────────────────────────────────────────
Template Literals 0.1ms HTML ⭐⭐⭐ ИСПОЛЬЗУЙТЕ
Bun.file() 0.05ms Файлы ⭐⭐⭐ ДЛЯ ФАЙЛОВ
Streaming 0.05ms Большие ⭐⭐⭐ БОЛЬШИЕ
JSON.stringify встроено JSON ⭐⭐⭐ ОПТИМИЗИРОВАН
React renderToString 2-5ms Компоненты ⭐⭐ КОГДА НУЖНЫ
HTML Builder Pattern 0.2ms Специальные ⭐⭐ РЕДКО
```
---
## 💡 Практические примеры
### Пример 1: Быстрая HTML страница
```typescript
export async function pageHandler(_req: Request): Promise<Response> {
const title = "My Page";
const content = "Hello World";
const html = `
<!DOCTYPE html>
<html>
<head><title>${title}</title></head>
<body>
<h1>${title}</h1>
<p>${content}</p>
</body>
</html>
`;
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8" }
});
}
```
### Пример 2: JSON API
```typescript
export async function apiHandler(_req: Request): Promise<Response> {
const data = {
status: "success",
data: [1, 2, 3],
timestamp: new Date().toISOString()
};
return new Response(JSON.stringify(data), {
headers: { "Content-Type": "application/json" }
});
}
```
### Пример 3: Статический файл
```typescript
export async function fileHandler(_req: Request): Promise<Response> {
return new Response(Bun.file("public/style.css"));
}
```
### Пример 4: Динамический контент
```typescript
export async function listHandler(_req: Request): Promise<Response> {
const items = ["Apple", "Banana", "Cherry"];
const html = `
<html>
<body>
<ul>
${items.map(item => `<li>${item}</li>`).join("")}
</ul>
</body>
</html>
`;
return new Response(html, {
headers: { "Content-Type": "text/html; charset=utf-8" }
});
}
```
---
## 📚 Файлы документации
| Файл | Описание |
|------|---------|
| `DOCS_INDEX.md` | Полный индекс документации |
| `BUN_CAPABILITIES.md` | 10 встроенных возможностей |
| `BUN_RENDERING.md` | Подробное руководство |
| `README.md` | Основная документация проекта |
---
## 🎓 Заключение
**Bun предоставляет все необходимые инструменты для веб-разработки БЕЗ дополнительных библиотек.**
### Главное правило:
```
Template Literals в 80% случаев
React когда нужны компоненты
Bun.file() для статических файлов
```
**Это всё, что вам нужно для высокопроизводительных веб-приложений!** 🚀