astro
Build content-focused websites with Astro: islands architecture, content collections, static generation, and integrations. Use for fast content sites.
Astro
Building fast content-focused websites with Astro.
Quick Start
npm create astro@latest
cd my-site && npm run devWhen to Use
- Blogs, docs, marketing sites
- Content-heavy static sites
- Sites needing minimal JS
- Islands for interactive pieces
Best Practices
Islands Architecture
- Ship zero JS by default
- Add interactivity with `client:load`, `client:visible`
- Keep islands small and isolated
- Use framework islands only where needed
Content Collections
- Use `src/content` collections with schemas
- Define zod schemas for frontmatter
- Query with `getCollection`
- Validate content in CI
Routing & Rendering
- Prefer static generation (`output: 'static'`)
- Use `getStaticPaths` for dynamic routes
- Add SSR only for dynamic needs
- Optimize images with `astro:assets`
Performance
- Set image sizes and formats
- Use `preload` for critical assets
- Avoid layout shift
- Keep JS budget per page
Dependencies
npm create astro@latest -- --template blog
npm i astroExamples
---
// Frontmatter for a page
import Layout from "../layouts/Base.astro";
export const title = "Home";
---
<Layout>
<h1>Welcome</h1>
</Layout>---
// Content collection query
import { getCollection } from "astro:content";
const posts = await getCollection("blog");
---
<ul>
{posts.map(p => <li><a href={`/blog/${p.slug}`}>{p.data.title}</a></li>)}
</ul><!-- Interactive island -->
<Counter client:visible />---
export async function getStaticPaths() {
const posts = await getCollection("blog");
return posts.map(p => ({ params: { slug: p.slug }, props: { post: p } }));
}
---
<p>{Astro.props.post.data.body}</p>Step-by-Step
1. Scaffold with `create astro`.
2. Set up content collections with schemas.
3. Build pages and layouts.
4. Add islands for interactive pieces.
5. Generate static paths for dynamic content.
6. Optimize images and assets.
7. Add SEO meta and RSS.
8. Deploy to a static host.
Validation
1. `npm run build` produces static output
2. Pages ship minimal JS
3. Content collections validate
4. Images are optimized
5. Lighthouse scores high
Troubleshooting
- Too much JS: convert components to islands or static.
- Collection errors: fix the zod schema.
- Slow builds: cache and parallelize.
Astro (АстроДжейЭс)
Быстрые контентные сайты на Astro.
Быстрый старт
npm create astro@latest
cd my-site && npm run devКогда использовать
- Блоги, доки, маркетинговые сайты
- Контентные статические сайты
- Сайты с минимумом JS
- Острова (islands) для интерактива
Лучшие практики
Islands архитектура
- Ноль JS по умолчанию
- Интерактив через `client:load`, `client:visible`
- Острова маленькие и изолированные
- Framework-острова только где нужно
Content collections
- `src/content` с схемами
- Zod-схемы для frontmatter
- Запросы через `getCollection`
- Валидация контента в CI
Маршрутизация и рендер
- Статическая генерация (`output: 'static'`)
- `getStaticPaths` для динамических маршрутов
- SSR только для динамики
- Оптимизация изображений через `astro:assets`
Производительность
- Размеры и форматы изображений
- `preload` для критичных ассетов
- Без layout shift
- JS-бюджет на страницу
Зависимости
npm create astro@latest -- --template blog
npm i astroПримеры
---
// Frontmatter страницы
import Layout from "../layouts/Base.astro";
export const title = "Home";
---
<Layout>
<h1>Welcome</h1>
</Layout>---
// Запрос content collection
import { getCollection } from "astro:content";
const posts = await getCollection("blog");
---
<ul>
{posts.map(p => <li><a href={`/blog/${p.slug}`}>{p.data.title}</a></li>)}
</ul><!-- Интерактивный остров -->
<Counter client:visible />---
export async function getStaticPaths() {
const posts = await getCollection("blog");
return posts.map(p => ({ params: { slug: p.slug }, props: { post: p } }));
}
---
<p>{Astro.props.post.data.body}</p>Пошаговое руководство
1. Скаффолд через `create astro`.
2. Настройте content collections со схемами.
3. Соберите страницы и layout.
4. Добавьте острова для интерактива.
5. Статические пути для динамического контента.
6. Оптимизируйте изображения и ассеты.
7. Добавьте SEO-мету и RSS.
8. Деплой на статический хост.
Валидация
1. `npm run build` даёт статический вывод
2. Страницы отдают минимум JS
3. Content collections валидны
4. Изображения оптимизированы
5. Lighthouse высокий
Устранение неполадок
- Слишком много JS: конвертируйте компоненты в острова или статику.
- Ошибки коллекций: исправьте zod-схему.
- Медленные сборки: кэшируйте и распараллеливайте.