Мы выпустили Astro 2.5 с большим списком функций:
- Data collections and references: в
src/content/теперь можно хранить JSON и YAML. Данные можно ссылать из других коллекций. - Hybrid rendering (experimental): server routes в преимущественно статических сайтах.
- Custom client directives (experimental): API для интеграций — свои механики загрузки для
client:директив. - HTML minification: опция минификации шаблонов Astro.
- Parallelized rendering: Astro рендерит соседние компоненты параллельно.
- Polymorphic type helper: компонент с теми же props, что и встроенные элементы.
Data collections and references
Content collections — first-class решение Astro для контента. Astro 2.5 расширяет историю новыми форматами данных и ссылками между коллекциями.
Добавлено свойство type: 'data' для JSON и YAML в отдельных коллекциях — профили авторов, alt-тексты, словари переводов и др.
Создавайте data collections рядом с content collections:
src/content/ blog/ week-1.md week-2.md authors/ grace-hopper.json alan-turing.jsonНастройка через type: 'data':
import { defineCollection, z } from "astro:content"
const authors = defineCollection({ type: "data", schema: z.object({ name: z.string(), socialLink: z.string().url(), }),})
const blog = defineCollection({ type: "content", schema: z.object({ /* ... */ }),})
export const collections = { blog: blog, authors: authors }Можно ссылаться на связанные записи — пост ссылается на профиль автора в JSON или на связанные URL. Связи настраиваются через reference():
import { defineCollection, reference, z } from "astro:content"
const blog = defineCollection({ type: "content", schema: z.object({ title: z.string(), // Reference a single author from the `authors` collection by `id` author: reference("authors"), // Reference an array of related posts from the `blog` collection by `slug` relatedPosts: z.array(reference("blog")), }),})
const authors = defineCollection({ type: "data", schema: z.object({ /** ... */ }),})
export const collections = { blog, authors }Каждый пост может ссылаться на связанные записи с типобезопасной валидацией:
---title: "Welcome to my blog"author: ben-holmes # references `src/content/authors/ben-holmes.json`relatedPosts: - about-me # references `src/content/blog/about-me.md` - my-year-in-review # references `src/content/blog/my-year-in-review.md`---См. обновлённое руководство content collections.
Static by default hybrid rendering (experimental)
В 2.0 можно было pre-render отдельные страницы в SSR-приложениях. В 2.5 — обратное: в преимущественно статическом сайте некоторые маршруты не pre-render.
Новый 'hybrid' output переворачивает поведение SSR по умолчанию — не нужно помечать каждый статический маршрут. Опция экспериментальна на короткий период. Включите hybridOutput и добавьте adapter:
astro.config.mjs
import { defineConfig } from "astro/config"import nodejs from "@astrojs/node"
export default defineConfig({ output: "hybrid", adapter: nodejs(), experimental: { hybridOutput: true, },})Весь сайт pre-render по умолчанию. Opt-out через prerender = false:
src/pages/contact.astro
---export const prerender = false
if (Astro.request.method === "POST") { // handle form submission}---
<form method="POST"> <input type="text" name="name" /> <input type="email" name="email" /> <button type="submit">Submit</button></form>Custom client directives (experimental)
Авторы интеграций могут определять новые client: директивы для контроля загрузки компонентов.
Добавление через addClientDirective() в astro:config:setup. Включите customClientDirectives в experimental.
astro.config.mjs
import { defineConfig } from "astro/config"import onClickDirective from "astro-click-directive"
export default defineConfig({ integrations: [onClickDirective()], experimental: { customClientDirectives: true, },})astro-click-directive
export default function onClickDirective() { return { hooks: { "astro:config:setup": ({ addClientDirective }) => { addClientDirective({ name: "click", entrypoint: "astro-click-directive/click.js", }) }, }, }}Теперь client:click на framework-компонентах с полной типизацией.
<Counter client:click />См. документацию client directives.
HTML minification
Opt-in минификация HTML от компонентов Astro.
С compressHTML Astro удаляет пробелы, включая переносы строк.
Минификация без ущерба производительности: для SSR минификация на каждый render дорога. С compressHTML компоненты сжимаются один раз компилятором Astro при сборке.
import { defineConfig } from "astro/config"export default defineConfig({ compressHTML: true,})Примечание: сжатие в dev и в финальной сборке.
HTML от framework-компонентов не сжимается — можно написать middleware для сжатия ответов.
Parallelized rendering
Astro рендерит компоненты параллельно — компоненты с загрузкой данных выше в дереве не блокируют соседние:
<Delayed ms={30} /><Delayed ms={20} /><Delayed ms={40} /><Delayed ms={10} /><Delayed /> ждёт миллисекунды. Раньше каждый ждал предыдущий. В 2.5 все рендерятся одновременно.
Мы пытались добавить это раньше, но не хватало бенчмарков. Улучшения CI-бенчмаркинга позволили внедрить с уверенностью.
Polymorphic type helper
Astro включает TypeScript helper (Polymorphic) для компонентов, рендерящихся как разные HTML-элементы с полной типобезопасностью. Полезно для <Link> как <a> или <button>.
Пример полностью типизированного полиморфного компонента. HTMLTag гарантирует, что as — валидный HTML-элемент.
---import { HTMLTag, Polymorphic } from "astro/types"
type Props<Tag extends HTMLTag> = Polymorphic<{ as: Tag }>
const { as: Tag, ...props } = Astro.props---
<Tag {...props} />More
В релизе также исправления и улучшения. См. release notes.
