API 参考
Astro global
段落标题 Astro globalAstro global 在 .astro 文件的所有上下文中都可用。它具有以下功能:
Astro.glob()
段落标题 Astro.glob()Astro.glob() 可以在静态网站 setup 中加载本地文件:
---const posts = await Astro.glob('../pages/post/*.md'); // 返回位于 ./src/pages/post/*.md 的数组并存储在常量 posts 中---
<div>{posts.slice(0, 3).map((post) => ( <article> <h1>{post.frontmatter.title}</h1> <p>{post.frontmatter.description}</p> <a href={post.frontmatter.url}>Read more</a> </article>))}</div>.glob() 只需要一个参数:你想导入的本地文件相对 glob URL。它是异步的并返回数组,这个数组包含匹配文件的导出内容。
.glob() 不接受使用变量或字符串进行插值,因为它们不是静态可分析的。(参见故障排查以了解解决方法)。这是因为 Astro.glob() 是 Vite 的 import.meta.glob() 的包装器。
你也可以在你的 Astro 项目中使用 import.meta.glob()。你可能想在以下情况下这样做:
- 你在一个不是
.astro的文件中需要这个功能,比如一个 API 路由。Astro.glob()只在.astro文件中可用,而import.meta.glob()在项目的任何地方都可用。 - 你不希望立即加载每个文件。
import.meta.glob()可以返回导入文件内容的函数,而不是返回内容本身。请注意,此导入包括任何导入文件的所有样式和脚本。无论文件是否被实际使用,这些样式和脚本都将被捆绑并添加到页面中,因为这是由静态分析决定的,而不是在运行时决定的。 - 你想访问每个文件的路径。
import.meta.glob()返回文件路径到其内容的映射,而Astro.glob()返回内容的列表。 - 你想传递多种模式;例如,你想添加一个“负模式”,过滤掉某些文件。
import.meta.glob()可以选择接受 glob 字符串数组,而不是单个字符串。
在 Vite 文档中阅读更多内容。
Markdown 文件
段落标题 Markdown 文件Markdown 文件有以下接口:
export interface MarkdownInstance<T extends Record<string, any>> { /* 在此文件的 YAML frontmatter 中指定的任何数据 */ frontmatter: T; /* 该文件的文件路径 */ file: string; /* 该文件的渲染路径 */ url: string | undefined; /* 渲染此文件内容的 Astro 组件 */ Content: AstroComponent; /* 返回该文件中 h1...h6 元素数组的函数 */ getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;}你可以选择使用 TypeScript 泛型指定 frontmatter 变量类型:
---interface Frontmatter { title: string; description?: string;}const posts = await Astro.glob<Frontmatter>('../pages/post/*.md');---
<ul> {posts.map(post => <li>{post.frontmatter.title}</li>)}</ul>Astro 文件
段落标题 Astro 文件Astro 文件具有以下接口:
export interface AstroInstance { /* 此文件的文件路径 */ file: string; /* 此文件的 URL(如果它在 pages 目录中)*/ url: string | undefined; default: AstroComponent;}其他文件
段落标题 其他文件其他文件可能有各种不同的接口,但如果你不知道文件类型包含什么,那么 Astro.glob() 可以接受 TypeScript 泛型。
---interface CustomDataFile { default: Record<string, any>;}const data = await Astro.glob<CustomDataFile>('../data/**/*.js');---Astro.props
段落标题 Astro.propsAstro.props 是一个包含任何作为组件属性传递的值的对象。.md 和 .mdx 文件的布局组件接收作为参数的 frontmatter 值。
---const { title, date } = Astro.props;---<div> <h1>{title}</h1> <p>{date}</p></div>---import Heading from '../components/Heading.astro';---<Heading title="我的第一篇文章" date="09 Aug 2022" />Astro.params
段落标题 Astro.paramsAstro.params 是一个包含与此请求匹配的动态路由段的值的对象。
在静态构建中,这将是 getStaticPaths() 返回的params,用于预渲染动态路由.。
在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。
---export function getStaticPaths() { return [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ];}
const { id } = Astro.params;---<h1>{id}</h1>另见:params
Astro.request
段落标题 Astro.requestAstro.request 是标准的 Request 对象。它可以用来获取请求的 url、headers、method,甚至是 body。可以使用 new URL(Astro.request.url) 来获得链接对象。
<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p><p>Received request headers: <code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code>另见:Astro.url
默认的 output: static 选项中,Astro.request.url 不包含搜索参数,如 ?foo=bar,因为在静态构建中不可能提前确定这些参数。但是在 output: 'server' 模式下,Astro.request.url 可以包含搜索参数,因为它可以从服务器请求中确定。
Astro.response
段落标题 Astro.responseAstro.response 是标准的 ResponseInit 对象,它具有以下结构:
status:响应的状态码,例如200。statusText:响应状态码与之相对应的状态信息,例如OK。headers:一个能让你为响应设置 HTTP 头部的Headers实例。
所以 Astro.response 也用于设置页面响应的 status、statusText 和 headers。
---if(condition) { Astro.response.status = 404; Astro.response.statusText = 'Not found';}---或者设置 header:
---Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');---Astro.cookies
段落标题 Astro.cookies
添加于:
astro@1.4.0
Astro.cookies 包含用于在服务端渲染模式下读取和操作 cookie 的工具方法。
get
段落标题 get类型: (key: string, options?: CookieGetOptions) => AstroCookie
获取 AstroCookie 对象形式的 cookie,该对象包含value和用于将 cookie 转换为非字符串类型的工具方法。
has
段落标题 has类型: (key: string) => boolean
用于判断 cookie 是否存在。如果这个 cookie 已经通过Astro.cookies.set()设置,这将返回 true,否则它将检查 Astro.request 中的 cookies。
set
段落标题 set类型: (key: string, value: string | number | boolean | object, options?: CookieSetOptions) => void
将 cookie key 设置为给定的值。这将试图把 cookie 的值转换为一个字符串。选项提供了设置 cookie 功能的方法,例如 maxAge 或 httpOnly。
delete
段落标题 delete类型: (key: string, options?: CookieDeleteOptions) => void
通过设置过去的到期日期(Unix 时间为 0)使 cookie 失效。
一旦 Cookie 被 “删除”(过期),Astro.cookies.has() 将返回 false,Astro.cookies.get() 将返回一个 value 为 undefined 的 AstroCookie。删除 Cookie 时可用的选项包括:domain、path、httpOnly、sameSite 和 secure。
headers
段落标题 headers类型: () => Iterator<string>
获取将与响应一起发送的 Set-Cookie 的 header 的值。
AstroCookie
段落标题 AstroCookie通过 Astro.cookies.get() 获取 cookie 返回一个 AstroCookie 类型。它具有以下结构。
value
段落标题 value类型: string | undefined
cookie 的原始字符串值。
json
段落标题 json类型: () => Record<string, any>
通过 JSON.parse() 解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出异常。
number
段落标题 number类型: () => number
将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。
boolean
段落标题 boolean类型: () => boolean
转换 cookie 的值为 boolean 类型。
CookieGetOptions
段落标题 CookieGetOptions
添加于:
astro@4.1.0
获取 cookie 允许通过 CookieGetOptions 接口指定选项:
decode
段落标题 decode类型: (value: string) => string
允许自定义如何将 cookie 反序列化为值。
CookieSetOptions
段落标题 CookieSetOptions
添加于:
astro@4.1.0
通过 Astro.cookies.set() 设置 cookie, 允许传入 CookieSetOptions 来自定义 cookie 如何被序列化。
domain
段落标题 domain类型: string
Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.
指定域。如果未设置域,则大多数客户端将解释为应用于当前域。
expires
段落标题 expires类型: Date
指定 cookie 过期日期。
httpOnly
段落标题 httpOnly类型: boolean
如果为 true,则客户端将无法访问该 Cookie。
maxAge
段落标题 maxAge类型: number
以秒为单位指定 cookie 有效的时间。
path
段落标题 path类型: string
指定应用 cookie 的域的子路径。
sameSite
段落标题 sameSite类型: boolean | 'lax' | 'none' | 'strict'
指定 SameSite cookie header 的值。
secure
段落标题 secure类型: boolean
如果为 true,则该 Cookie 仅在 https 网站上设置。
encode
段落标题 encode类型: (value: string) => string
允许自定义 cookie 序列化方式。
Astro.redirect()
段落标题 Astro.redirect()允许你重定向到另一个页面,并可选地提供一个 HTTP 响应状态码 作为第二个参数。
页面(而不是子组件)必须 return Astro.redirect() 的结果,以便重定向发生。
以下示例将用户重定向到登录页面,使用默认的 HTTP 响应状态码 302:
---import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// 如果用户未登录,则将其重定向到登录页面if (!isLoggedIn(cookie)) { return Astro.redirect('/login');}---Astro.canonicalURL
段落标题 Astro.canonicalURL使用 Astro.url 来构建你自己的标准链接。
当前页面的标准链接。
Astro.url
段落标题 Astro.url
添加于:
astro@1.0.0-rc
URL对象,由当前 Astro.request.url 的链接字符串值构成。对于与请求的链接的个别属性进行交互是有用的,如路径名和起源。
相当于做 new URL(Astro.request.url)。
<h1>当前链接是:{Astro.url}</h1><h1>当前链接路径名是:{Astro.url.pathname}</h1><h1>当前链接源是:{Astro.url.origin}</h1>你也可以使用 Astro.url 来创建新的链接,并把它作为参数传给 new URL()。
---// 示例:使用你的生产域名构建一个规范的URLconst canonicalURL = new URL(Astro.url.pathname, Astro.site);// 示例:使用你目前的域名构建一个用于 SEO meta 标签的URLconst socialImageURL = new URL('/images/preview.png', Astro.url);---<link rel="canonical" href={canonicalURL} /><meta property="og:image" content={socialImageURL} />Astro.clientAddress
段落标题 Astro.clientAddress
添加于:
astro@1.0.0-rc
指定请求的 IP 地址。这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
---const ip = Astro.clientAddress;---
<div>你的 IP 地址是:<span class="address">{ ip }</span></div>Astro.site
段落标题 Astro.siteAstro.site 返回根据 Astro 配置中的 site 生成的 URL。如果未定义 Astro 配置中的 site,Astro.site 也不会被定义。
Astro.generator
段落标题 Astro.generator
添加于:
astro@1.0.0
Astro.generator 是个便捷方法,它可以添加与你当前 Astro 版本一致的 <meta name="generator"> 标签。它遵循的格式是 "Astro v1.x.x"。
<html> <head> <meta name="generator" content={Astro.generator} /> </head> <body> <footer> <p>由 <a href="https://astro.build">{Astro.generator}</a> 构建</p> </footer> </body></html>Astro.slots
段落标题 Astro.slotsAstro.slots 包含修改 Astro 组件插槽的工具函数。
Astro.slots.has()
段落标题 Astro.slots.has()类型:(slotName: string) => boolean
你可以使用 Astro.slots.has() 检查特定插槽名称的内容是否存在。当你想要包装插槽内容,但只想在使用插槽时呈现包装器元素时,这会很有用。
------<slot />
{Astro.slots.has('more') && ( <aside> <h2>More</h2> <slot name="more" /> </aside>)}Astro.slots.render()
段落标题 Astro.slots.render()类型:(slotName: string, args?: any[]) => Promise<string>
你可以使用 Astro.slots.render() 将插槽的内容异步渲染为 HTML 字符串。
---const html = await Astro.slots.render('default');---<Fragment set:html={html} />这是针对高级用例的!在大多数情况下,使用 <slot /> 元素呈现插槽内容会更简单。
Astro.slots.render() 还可以接受第二个参数:一个参数数组,该参数数组将被转发给任何函数子组件。这对于自定义实用程序组件很有用。
举个例子,这个 <Shout /> 组件将它的 message 属性转换为大写,并将其传递给默认插槽:
---const message = Astro.props.message.toUpperCase();let html = '';if (Astro.slots.has('default')) { html = await Astro.slots.render('default', [message]);}---<Fragment set:html={html} />作为 <Shout /> 的子级传递的回调函数将会接收到大写的 message 参数:
---import Shout from "../components/Shout.astro";---<Shout message="slots!"> {(message) => <div>{message}</div>}</Shout>
<!-- 渲染成 <div>SLOTS!</div> -->Astro.self
段落标题 Astro.selfAstro.self 允许 Astro 组件被递归调用。这使得你可以通过在组件模板中使用 <Astro.self> 从自身内部渲染 Astro 组件。这对遍历大型数据存储和嵌套数据结构很有帮助。
---const { items } = Astro.props;---<ul class="nested-list"> {items.map((item) => ( <li> <!-- 如果有嵌套的数据结构,将渲染 `<Astro.self>` --> <!-- 并可以通过递归调用来传递参数 --> {Array.isArray(item) ? ( <Astro.self items={item} /> ) : ( item )} </li> ))}</ul>然后,这个组件可以这样用:
---import NestedList from './NestedList.astro';---<NestedList items={['A', ['B', 'C'], 'D']} />之后将会渲染这样的 HTML:
<ul class="nested-list"> <li>A</li> <li> <ul class="nested-list"> <li>B</li> <li>C</li> </ul> </li> <li>D</li></ul>Astro.locals
段落标题 Astro.localsAstro.locals 是一个对象,包含来自中间件的 context.locals对象的任何值。使用该对象可访问中间件在你的 .astro 文件中返回的数据。
---const title = Astro.locals.welcomeTitle();const orders = Array.from(Astro.locals.orders.entries());---<h1>{title}</h1><ul> {orders.map(order => { return <li>{ /* 每单都有收获 */ }</li> })}</ul>Astro.preferredLocale
段落标题 Astro.preferredLocaleAstro.preferredLocale 是一个代表当前用户的首选语言环境的计算出的值。
它是通过检查 i18n.locales 数组中配置的语言环境和用户浏览器通过头部 Accept-Language 指定的语言环境来计算的。如果不存在匹配项则该值为 undefined。
这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
Astro.preferredLocaleList
段落标题 Astro.preferredLocaleListAstro.preferredLocaleList 是一个同时被浏览器请求并且你的网站也支持的语言环境的数组。它是一个由你的网站和你的访客共同支持的语言环境的列表。
如果浏览器请求的语言环境没有在你的网站中被支持,那么该值为 []:你不支持你的访客的任何首选语言环境。
如果浏览器没有指定任何首选语言环境,那么该值将是 i18n.locales:你支持的所有语言环境都将被同等视为访客倾向的语言环境。
这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
Astro.currentLocale
段落标题 Astro.currentLocale从当前 URL 使用你的 locales 配置中指定的语法计算出的语言环境。如果 URL 不包含 /[locale]/ 前缀,则该值将默认为 i18n.defaultLocale。
端点上下文
段落标题 端点上下文端点函数接收一个上下文对象作为第一个参数。它与许多 Astro 全局属性相似。
import type { APIContext } from 'astro';
export function GET(context: APIContext) { // ...}context.params
段落标题 context.paramscontext.params 是一个对象,其中包含与此请求匹配的动态路由段的值。
在静态构建中,这将是用于预渲染动态路由的 getStaticPaths() 返回的 params。
在 SSR 构建中,这可以是与动态路由模式中的路径段匹配的任何值。
import type { APIContext } from 'astro';
export function getStaticPaths() { return [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ];}
export function GET({ params }: APIContext) { return new Response( JSON.stringify({ id: params.id }), );}另见:params
context.props
段落标题 context.propscontext.props 是一个对象,其中包含从 getStaticPaths() 传递的任何 props。由于在为 SSR 构建时不使用 getStaticPaths(),因此 context.props 仅在静态构建中可用。
import type { APIContext } from 'astro';
export function getStaticPaths() { return [ { params: { id: '1' }, props: { author: 'Blu' } }, { params: { id: '2' }, props: { author: 'Erika' } }, { params: { id: '3' }, props: { author: 'Matthew' } } ];}
export function GET({ props }: APIContext) { return new Response( JSON.stringify({ author: props.author }), );}另见:通过props传递数据
context.request
段落标题 context.request一个标准的 Request 对象。它可以用来获取请求的 url、headers、method 甚至是 body。
import type { APIContext } from 'astro';
export function GET({ request }: APIContext) { return new Response(`Hello ${request.url}`);}context.cookies
段落标题 context.cookiescontext.cookies 包含用于读取和操作 cookie 的工具。
context.url
段落标题 context.urlcontext.url 是一个 URL 对象,它是从当前 context.request.url URL 字符串值构造的。
另见:Astro.url
context.clientAddress
段落标题 context.clientAddress指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。
import type { APIContext } from 'astro';
export function GET({ clientAddress }: APIContext) { return new Response(`Your IP address is: ${clientAddress}`);}context.site
段落标题 context.sitecontext.site 返回一个由 Astro 配置中的 site 生成的 URL。如果未定义,则将返回从 localhost 生成的 URL。
另见:Astro.site
context.generator
段落标题 context.generatorcontext.generator 是一个方便的方法,用于指示项目正在运行的 Astro 版本。它遵循 "Astro v1.x.x" 的格式。
import type { APIContext } from 'astro';
export function GET({ generator, site }: APIContext) { const body = JSON.stringify({ generator, site }); return new Response(body);}context.redirect()
段落标题 context.redirect()context.redirect() 返回一个 Response 对象,允许你重定向到另一个页面。此函数仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。
import type { APIContext } from 'astro';
export function GET({ redirect }: APIContext) { return redirect('/login', 302);}context.locals
段落标题 context.localscontext.locals 是一个对象,用于在请求的生命周期内存储和访问任意信息。
中间件函数可以读写context.locals的值:
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = ({ locals }, next) => { if (!locals.title) { locals.title = "Default Title"; } return next();}API 端点只能从 context.locals中读取信息:
import type { APIContext } from 'astro';
export function get({ locals }: APIContext) { return new Response(locals.title); // "默认标题"}另见:Astro.locals
getStaticPaths()
段落标题 getStaticPaths()如果页面在文件名中使用动态参数,该组件将需要导出一个 getStaticPaths() 函数。
必须要有该函数,因为 Astro 是静态站点生成器。这意味着整个网站是预构建的。如果 Astro 不知道在构建时生成什么页面,你的用户在访问你的网站时就看不到它。
---export async function getStaticPaths() { return [ { params: { /* 必需 */ }, props: { /* 可选 */ } }, { params: { ... } }, { params: { ... } }, // ... ];}---<!-- 你的 HTML 模板在这里 -->getStaticPaths() 函数应该返回对象数组,以确定哪些路径会被 Astro 预渲染。
getStaticPaths() 函数在会任何页面加载之前,在它自己的隔离范围内执行一次。因此,除了文件导入之外,你不能从它的父作用域中引用任何东西。如果你违反了这个要求,编译器会发出警告。
params
段落标题 params每个返回对象的 params 键都会告诉 Astro 要构建什么路由。返回参数必须映射到你的组件文件路径中定义的动态参数和其余参数。
params 被编码到链接中,所以只能由字符串作为值。每个 params 对象的值必须与页面名称中使用的参数一致。
比如说有 src/pages/posts/[id].astro 页面。如果你从这个页面导出 getStaticPaths 并返回以下的路由:
---export async function getStaticPaths() { return [ { params: { id: '1' } }, { params: { id: '2' } }, { params: { id: '3' } } ];}
const { id } = Astro.params;---<h1>{id}</h1>然后 Astro 会在构建时静态地生成 posts/1、posts/2 和 posts/3。
通过 props 传递数据
段落标题 通过 props 传递数据为了给每个生成的页面传递额外的数据,你也可以在每个返回的路径对象上设置 props 值。与 params 不同的是,props 没有被编码到链接中,所以并不局限于字符串。
例如,假设你根据从远程 API 获取的数据来生成页面。你可以将完整的数据对象传递给 getStaticPaths 中的页面组件。
---export async function getStaticPaths() { const data = await fetch('...').then(response => response.json());
return data.map((post) => { return { params: { id: post.id }, props: { post }, }; });}
const { id } = Astro.params;const { post } = Astro.props;---<h1>{id}: {post.name}</h1>你也可以传递普通数组,这在生成或缓存已知路径列表时可能会有帮助。
---export async function getStaticPaths() { const posts = [ {id: '1', category: "astro", title: "API Reference"}, {id: '2', category: "react", title: "Creating a React Counter!"} ]; return posts.map((post) => { return { params: { id: post.id }, props: { post } }; });}const {id} = Astro.params;const {post} = Astro.props;---<body> <h1>{id}: {post.title}</h1> <h2>Category: {post.category}</h2></body>然后 Astro 将在构建时使用 pages/posts/[id].astro 中的页面组件静态地生成 posts/1 和 posts/2。页面可以使用 Astro.props 引用这些数据。
paginate()
段落标题 paginate()分页是 Astro 通过 paginate() 函数原生支持网站的常见用例。paginate() 将自动生成数组,从getStaticPaths()返回,为分页集合的每个页面创建一个 URL。页面编号将作为参数传递,而页面数据将作为page道具传递。
export async function getStaticPaths({ paginate }) { // 用 fetch()、Astro.glob() 等加载你的数据 const response = await fetch(`https://pokeapi.co/api/v2/pokemon?limit=150`); const result = await response.json(); const allPokemon = result.results;
// 返回包含分页的所有帖子的路由集合 return paginate(allPokemon, { pageSize: 10 });}
// 如果设置正确,现在页面已经具备了渲染单页所需的一切参数(见下一节)。const { page } = Astro.props;paginate():假定文件名为 [page].astro 或 [...page].astro。page 参数将是链接中的页数。
/posts/[page].astro:会产生/posts/1、/posts/2、/posts/3等链接。/posts/[...page].astro:将产生/posts、/posts/2/posts/3等链接。
paginate() 函数具有以下参数:
pageSize- 每页显示的项目数params- 用于创建动态路由的附加参数props- 在每个页面上可用的附加属性
page 分页参数
段落标题 page 分页参数分页会给每个渲染的页面传递 page 参数,代表分页集合中的单页数据。这包括你分页的数据(page.data)以及该页的元数据(page.url、page.start、page.end、page.total 等)。这些元数据对诸如“下一页”按钮或“显示 100 个中前十个”的信息很有用。
page.data
段落标题 page.data类型: Array
从 data() 中返回当前页面数据数组。
page.start
段落标题 page.start类型: number
当前页第一个项目的索引,从 0 开始(例如,如果 pageSize: 25,第一页该值未 0,第二页为25,以此类推)。
page.end
段落标题 page.end类型: number
当前页面最后一条数据的索引。
page.size
段落标题 page.size类型: number
每个页面有多少条数据。
page.total
段落标题 page.total类型: number
所有数据的总数量。
page.currentPage
段落标题 page.currentPage类型: number
当前页码,从 1 开始。
page.lastPage
段落标题 page.lastPage类型: number
总页数。
page.url.current
段落标题 page.url.current类型: string
获取当前页面的链接(对规范链接很有用)。
page.url.prev
段落标题 page.url.prev类型: string | undefined
获取上一页链接(如果在首页,将是undefined)。
page.url.next
段落标题 page.url.next类型: string | undefined
获取下一页链接(如果没有更多的页面,将是undefined)。
import.meta
段落标题 import.meta所有 ESM 模块都包含 import.meta 属性。Astro 基于 Vite 增加了 import.meta.env。
import.meta.env.SSR 可以用来了解何时在服务器渲染。有时你可能想要不同的逻辑,例如,某个组件应该只在客户端渲染:
export default function () { return import.meta.env.SSR ? <div class="spinner"></div> : <FancyComponent />;}图像(astro:assets)
段落标题 图像(astro:assets)getImage()
段落标题 getImage()getImage() 依赖于仅在服务器上可用的 API,当在客户端使用时会导致构建失败。
getImage()函数旨在生成用于在 HTML 之外的其他地方所使用的图像,例如在 API 路由 中。它还允许你创建自定义的 <Image /> 组件。
getImage() 函数接受一个选项对象,其中包含与 Image 组件相同的属性(除了 alt)。
---import { getImage } from "astro:assets";import myBackground from "../background.png"const optimizedBackground = await getImage({src: myBackground, format: 'avif'})---<div style={`background-image: url(${optimizedBackground.src});`}></div>它返回了一个包含了如下属性的对象:
{ options: {...} // 被传递的原始参数 src: "https//..." // 生成图片的路径 attributes: {...} // 额外的 HTML 属性,用于渲染图像(如宽度、高度、样式等)}内容集合(astro:content)
段落标题 内容集合(astro:content)
添加于:
astro@2.0.0
内容集合提供了 API 来配置和查询 src/content/ 中的 Markdown 或 MDX 文档。有关功能和用法示例,请参考内容集合指南。
defineCollection()
段落标题 defineCollection()defineCollection() 是一个用于在 src/content/config.* 文件中配置集合的工具函数。
import { z, defineCollection } from 'astro:content';const blog = defineCollection({ type: 'content', schema: z.object({ title: z.string(), permalink: z.string().optional(), }),});
// 将定义的集合公开给 Astro// 通过 `collections` 导出export const collections = { blog };这个函数接受以下属性:
type
段落标题 type
添加于:
astro@2.5.0
类型: 'content' | 'data'
默认: 'content'
type 是一个字符串,用于定义存储在集合中的条目的类型:
'content'- 用于内容创作格式,如 Markdown (.md)、MDX (.mdx) 或 Markdoc (.mdoc)'data'- 用于 JSON (.json) 或 YAML (.yaml) 等纯数据格式
这意味着集合不能存储内容和数据格式的混合。你必须按类型将这些条目分割成单独的集合。
schema
段落标题 schema类型:TSchema extends ZodType
schema 是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 Zod 验证器
有关示例请参考 内容集合指南
reference()
段落标题 reference()Type: (collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>
在内容配置中使用 reference() 函数来定义从一个集合到另一个集合的关系或 “引用”。该函数接受一个集合名称,并验证内容前置事项或数据文件中指定的条目标识符。
此示例定义了从博客作者到 “作者 “集合的引用,以及到同一 “博客 “集合的相关文章数组的引用:
import { defineCollection, reference, z } from 'astro:content';
const blog = defineCollection({ type: 'content', schema: z.object({ // 通过 "id "从 "作者 "集合中引用单个作者 author: reference('authors'), // 按 "slug "从 "blog "集合中引用相关帖子数组 relatedPosts: z.array(reference('blog')), })});
const authors = defineCollection({ type: 'data', schema: z.object({ /* ... */ })});
export const collections = { blog, authors };有关示例请参考 内容集合指南.
getCollection()
段落标题 getCollection()类型:(collection: string, filter?: (entry: CollectionEntry<collection>) => boolean) => CollectionEntry<collection>[]
getCollection() 是一个函数,用于通过集合名称检索内容集合条目列表。
默认情况下,它返回集合中的所有项目,并接受可选的 filter 函数来缩小条目属性。这允许你根据 id、slug 或 frontmatter 值(通过 data 对象)查询集合中的某些项目。
---import { getCollection } from 'astro:content';
// 获取 `src/content/blog/` 中的所有条目const allBlogPosts = await getCollection('blog');
// 仅返回 frontmatter 中 `draft: true` 的条目const draftBlogPosts = await getCollection('blog', ({ data }) => { return data.draft === true;});---有关示例请参考 内容集合指南 以获取示例用法。
getEntry()
段落标题 getEntry()
添加于:
astro@2.5.0
Types:
(collection: string, contentSlugOrDataId: string) => CollectionEntry<collection>({ collection: string, id: string }) => CollectionEntry<collection>({ collection: string, slug: string }) => CollectionEntry<collection>
getEntry() 是一个函数,可通过集合名称和条目 id (对于 type: 'data' 集合)或条目 slug (对于 type: 'content' 集合)检索单个集合条目。getEntry()也可用于获取引用条目,以访问data、body或render()属性:
---import { getEntry } from 'astro:content';
// 得到 `src/content/blog/enterprise.md`const enterprisePost = await getEntry('blog', 'enterprise');
// 得到 `src/content/captains/picard.yaml`const picardProfile = await getEntry('captains', 'picard');
// 得到 the profile referenced by `data.captain`const enterpriseCaptainProfile = await getEntry(enterprisePost.data.captain);---有关内容集合的示例,请参考 查询集合条目.
getEntries()
段落标题 getEntries()
添加于:
astro@2.5.0
Types:
(Array<{ collection: string, id: string }>) => Array<CollectionEntry<collection>>(Array<{ collection: string, slug: string }>) => Array<CollectionEntry<collection>>
getEntries() 是一个从同一集合中检索多个集合条目的函数。这对于返回引用条目的数组访问其关联的data、body和render()属性非常有用。
---import { getEntries } from 'astro:content';
const enterprisePost = await getEntry('blog', 'enterprise');
// 获取由 `data.relatedPosts` 引用的相关帖子const enterpriseRelatedPosts = await getEntries(enterprisePost.data.relatedPosts);---getEntryBySlug()
段落标题 getEntryBySlug()类型:(collection: string, slug: string) => CollectionEntry<collection>
使用 getEntry()函数 查询内容条目。该函数接受与 getEntryBySlug() 相同的参数,并支持通过 id 查询 JSON 或 YAML 集合。
getEntryBySlug() 是一个函数,用于通过集合名称和条目 slug 检索单个集合条目。
---import { getEntryBySlug } from 'astro:content';
const enterprise = await getEntryBySlug('blog', 'enterprise');---有关示例请参考 内容集合指南 以获取示例用法。
集合条目类型
段落标题 集合条目类型getCollection()和 getEntryBySlug() 函数都会返回 CollectionEntry 类型的条目。这个类型可以从 astro:content 中获取:
import type { CollectionEntry } from 'astro:content';CollectionEntry<TCollectionName> 类型是一个对象,具有以下值。 TCollectionName 是你正在查询的集合的名称(例如 CollectionEntry<'blog'>)。
id
段落标题 id适用于: type: 'content' and type: 'data' 集合
示例类型:
- content collections:
'entry-1.md' | 'entry-2.md' | ... - data collections:
'author-1' | 'author-2' | ...
一个使用相对于 src/content/[collection] 的文件路径的唯一 ID。根据集合条目文件路径枚举所有可能的字符串值。请注意,类型: 'content' 的集合在其 ID 中包含文件扩展名,而定义为 type: 'data' 的集合则不包含。
collection
段落标题 collection适用于: type: 'content' and type: 'data' 集合
示例类型: 'blog' | 'authors' | ...
src/content/` 下顶级文件夹的名称,条目位于该文件夹中。该名称用于在模式和查询函数中引用集合。
data
段落标题 data适用于: type: 'content' and type: 'data' 集合
类型:CollectionSchema<TCollectionName>
一个从集合模式推断出的 frontmatter 属性对象(参考 defineCollection())。如果没有配置模式,则默认为 any。
slug
段落标题 slug适用于: 仅仅 type: 'content' 集合
示例类型: 'entry-1' | 'entry-2' | ...
可用于 Markdown 或 MDX 文档的 URL 标头。默认为不含文件扩展名的 “id”,但可以通过在文件的 frontmatter 中设置slug属性来覆盖。
body
段落标题 body适用于: 仅 type: 'content' 集合
类型:string
一个包含 Markdown 或 MDX 文档原始未编译的 body 的字符串。
render()
段落标题 render()适用于: 仅 type: 'content' 集合
类型:() => Promise<RenderedEntry>
一个用于编译给定的 Markdown 或 MDX 文档以进行渲染的函数。它返回以下属性:
<Content />- 用于在 Astro 文件中渲染文档内容的组件。headings- 生成的标题列表,与 Astro 的getHeadings()工具函数相同 在 Markdown 和 MDX 导入中。remarkPluginFrontmatter- 在应用 remark 或 rehype 插件后修改后的 frontmatter 对象。设置为类型any。
---import { getEntryBySlug } from 'astro:content';const entry = await getEntryBySlug('blog', 'entry-1');
const { Content, headings, remarkPluginFrontmatter } = await entry.render();---有关示例请参考 内容集合指南 以获取示例用法。
其他内容集合类型
段落标题 其他内容集合类型astro:content 模块也导出了以下类型,供你在 Astro 项目中使用:
CollectionKey
段落标题 CollectionKey这是一个在 src/content/config.* 文件中定义的所有集合名称的字符串联合类型。当定义一个可以接受任何集合名称的通用函数时,这个类型很有用。
import type { CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) { return getCollection(collection);}ContentCollectionKey
段落标题 ContentCollectionKey一个在 src/content/config.* 文件中定义的所有 type: 'content' 集合名称的字符串联合类型。
DataCollectionKey
段落标题 DataCollectionKey一个在 src/content/config.* 文件中定义的所有 type: 'data' 集合名称的字符串联合类型。
SchemaContext
段落标题 SchemaContext即 defineCollection 在 schema 函数形状中所使用的 context 对象。当为多个集合构建可重用的模式时,这个类型很有用。
它包括了以下属性:
image()模式辅助工具允许你 在内容集合中使用本地图片。
import type { SchemaContext } from 'astro:content';
export const imageSchema = ({ image }: SchemaContext) => z.object({ image: image(), description: z.string().optional(), });
const blog = defineCollection({ type: 'content', schema: ({ image }) => z.object({ title: z.string(), permalink: z.string().optional(), image: imageSchema({ image }) }),});中间件(astro:middleware)
段落标题 中间件(astro:middleware)
添加于:
astro@2.6.0
中间件使你能拦截请求和响应,并在每次渲染页面或端点时动态注入行为。有关功能和用法示例,请参考中间件指南。
onRequest()
段落标题 onRequest()一个在 src/middleware.js 里的必须导出的函数,它将在每次渲染页面或端点时被调用。它接受两个可选参数:context 和 next()。onRequest() 必须返回一个 Response:要么直接返回,要么通过调用 next() 返回。
export function onRequest (context, next) { // 拦截一个请求的响应数据 // 可选修改响应 // 直接返回一个 Response 对象,或者调用 `next()` 的结果 return next();};next()
段落标题 next()一个拦截(读取和修改)一个 Request 的 Response 或调用链中的“下一个(next)”中间件并返回一个 Response 的函数。例如,这个函数可以修改响应的 HTML 主体。
这是 onRequest() 的可选参数,并且可能会提供中间件返回的所需 Response。
sequence()
段落标题 sequence()一个接受中间件函数作为参数的函数,它将按照它们传递的顺序执行它们。
import { sequence } from "astro:middleware";
async function validation(_, next) {...}async function auth(_, next) {...}async function greeting(_, next) {...}
export const onRequest = sequence(validation, auth, greeting);createContext()
段落标题 createContext()一个底层 API,用于创建一个 APIContext 以传递给 Astro 中间件的 onRequest() 函数。
此函数可以由集成/适配器用于执行 Astro 中间件。
trySerializeLocals()
段落标题 trySerializeLocals()一个底层 API,它接受任何值并尝试返回它的序列化版本(一个字符串)。如果该值无法序列化,该函数将抛出一个运行时错误。
国际化(astro:i18n)
段落标题 国际化(astro:i18n)
添加于:
astro@3.5.0
此模块提供了一些函数,帮助你使用项目配置的语言环境设置创建 URL。
使用 i18n 路由为你的项目创建路由将依赖于你设置的某些配置值,这些值会影响你的页面路由。使用这些函数创建路由时,请确保考虑到你的个人设置,包括:
另外,请注意,这些函数为你的 defaultLocale 创建的返回 URL 将反映你的 i18n.routing 配置。
有关功能和使用示例,请参阅我们的 i18n 路由指南。
getRelativeLocaleUrl()
段落标题 getRelativeLocaleUrl()getRelativeLocaleUrl(locale: string, path?: string, options?: GetLocaleOptions): string
使用此函数来检索一个语言环境的相对路径。如果该语言环境不存在,Astro 会抛出一个错误。
---getRelativeLocaleUrl("fr");// 返回 /frgetRelativeLocaleUrl("fr", "");// 返回 /frgetRelativeLocaleUrl("fr", "getting-started");// 返回 /fr/getting-startedgetRelativeLocaleUrl("fr_CA", "getting-started", { prependWith: "blog"});// 返回 /blog/fr-ca/getting-startedgetRelativeLocaleUrl("fr_CA", "getting-started", { prependWith: "blog", normalizeLocale: false});// 返回 /blog/fr_CA/getting-started---getAbsoluteLocaleUrl()
段落标题 getAbsoluteLocaleUrl()getAbsoluteLocaleUrl(locale: string, path: string, options?: GetLocaleOptions): string
当 [site] 配置了值时,使用这个函数来检索一个语言环境的绝对路径。如果 [site] 没有被配置,该函数将返回一个相对 URL。如果语言环境不存在,Astro 会抛出一个错误。
---// 如果 `site` 被设置为 `https://example.com`getAbsoluteLocaleUrl("fr");// 返回 https://example.com/frgetAbsoluteLocaleUrl("fr", "");// 返回 https://example.com/frgetAbsoluteLocaleUrl("fr", "getting-started");// 返回 https://example.com/fr/getting-startedgetAbsoluteLocaleUrl("fr_CA", "getting-started", { prependWith: "blog"});// 返回 https://example.com/blog/fr-ca/getting-startedgetAbsoluteLocaleUrl("fr_CA", "getting-started", { prependWith: "blog", normalizeLocale: false});// 返回 https://example.com/blog/fr_CA/getting-started---getRelativeLocaleUrlList()
段落标题 getRelativeLocaleUrlList()getRelativeLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]
像使用 getRelativeLocaleUrl 那样使用此函数,返回所有语言环境的相对路径列表。
getAbsoluteLocaleUrlList()
段落标题 getAbsoluteLocaleUrlList()getAbsoluteLocaleUrlList(path?: string, options?: GetLocaleOptions): string[]
像使用 getAbsoluteLocaleUrl 那样使用此函数,返回所有语言环境的绝对路径列表。
getPathByLocale()
段落标题 getPathByLocale()getPathByLocale(locale: string): string
当配置了自定义语言环境路径时,此函数返回与一个或多个 codes 关联的 path。
export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }})---getPathByLocale("fr"); // 返回 "french"getPathByLocale("fr-CA"); // 返回 "french"---getLocaleByPath
段落标题 getLocaleByPathgetLocaleByPath(path: string): string
此函数返回与语言环境 path 关联的 code。
export default defineConfig({ i18n: { locales: ["es", "en", { path: "french", codes: ["fr", "fr-BR", "fr-CA"] }] }})---getLocaleByPath("french"); // 返回 "fr",因为这是首个配置的代码---redirectToDefaultLocale()
段落标题 redirectToDefaultLocale()redirectToDefaultLocale(context: APIContext, statusCode?: ValidRedirectStatus): Promise<Response>
添加于:
astro@4.6.0
仅当 i18n.routing 设置为 "manual" 时可用。
此函数返回一个 Response,将重定向到配置的 defaultLocale。它接受一个可选的有效重定向状态码。
import { defineMiddleware } from "astro:middleware";import { redirectToDefaultLocale } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => { if (context.url.pathname.startsWith("/about")) { return next(); } else { return redirectToDefaultLocale(context, 302); }})redirectToFallback()
段落标题 redirectToFallback()redirectToFallback(context: APIContext, response: Response): Promise<Response>
添加于:
astro@4.6.0
仅当 i18n.routing 设置为 "manual" 时可用。
此函数允许你在自己的中间件中使用你的 i18n.fallback 配置。
import { defineMiddleware } from "astro:middleware";import { redirectToFallback } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => { const response = await next(); if (response.status >= 300) { return redirectToFallback(context, response) } return response;})notFound()
段落标题 notFound()notFound(context: APIContext, response: Response): Promise<Response>
添加于:
astro@4.6.0
仅当 i18n.routing 设置为 "manual" 时可用。
当以下情况发生时,在你的路由中间件中使用此函数来返回一个 404 错误:
- 当前路径不是根路径。例如:
/或/<base> - URL 中不包含语言环境代码
当传递了一个 Response,由此函数发出的新 Response 将包含原始响应的相同头信息。
import { defineMiddleware } from "astro:middleware";import { notFound } from "astro:i18n";
export const onRequest = defineMiddleware((context, next) => { const pathNotFound = notFound(context); if (pathNotFound) { return pathNotFound; } return next();})middleware()
段落标题 middleware()middleware(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean })
添加于:
astro@4.6.0
仅当 i18n.routing 设置为 "manual" 时可用。
此函数允许你以编程方式创建 Astro i18n 中间件。
当你仍然想要使用默认的 i18n 逻辑,但只在你的网站添加少数例外时,这个功能非常有用。
import { middleware } from "astro:i18n";import { sequence, defineMiddleware } from "astro:middleware";
const customLogic = defineMiddleware(async (context, next) => { const response = await next(); // 在这里解析响应后的自定义逻辑。 // 可以捕获来自 Astro i18n 中间件的响应。
return response;});
export const onRequest = sequence(customLogic, middleware({ prefixDefaultLocale: true, redirectToDefaultLocale: false}))requestHasLocale()
段落标题 requestHasLocale()requestHasLocale(context: APIContext): boolean
添加于:
astro@4.6.0
仅当 i18n.routing 设置为 "manual" 时可用。
检查当前 URL 是否包含已配置的语言环境代码。在内部,此函数将使用 APIContext#url.pathname。
import { defineMiddleware } from "astro:middleware";import { requestHasLocale } from "astro:i18n";
export const onRequest = defineMiddleware(async (context, next) => { if (requestHasLocale(context)) { return next(); } return new Response("Not found", { status: 404 });})内置组件
段落标题 内置组件Astro 包括几个内置的组件供你在你的项目中使用。在 .astro 文件中可以通过 import {} from 'astro:components'; 引用所有的内置组件。
<Code />
段落标题 <Code />---import { Code } from 'astro:components';---<!-- 使用语法凸显部分 JavaScript 代码--><Code code={`const foo = 'bar';`} lang="js" /><!-- 可选:定制你的主题 --><Code code={`const foo = 'bar';`} lang="js" theme="dark-plus" /><!-- 可选:启用文字包装 --><Code code={`const foo = 'bar';`} lang="js" wrap /><!-- Optional: Output inline code. --><p> <Code code={`const foo = 'bar';`} lang="js" inline /> will be rendered inline.</p>该组件在构建时为代码块提供语法高亮(不包括客户端 JavaScript)。该组件由 Shiki 驱动,它支持所有流行的主题和语言。另外,你可以通过给 theme 和 lang 传递自定义主题和语言分别添加它们。
<Fragment />
段落标题 <Fragment />一个与 set:* 指令 一起使用的组件,用于渲染 HTML 内容而不添加任何额外的包裹元素。
---const htmlString = '<p>Raw HTML content</p>';---<Fragment set:html={htmlString} />请参见在 Astro 语法中使用片段的更多信息。
<Prism />
段落标题 <Prism />要安装 Prism 高亮器组件,需要先安装 @astrojs/prism 包:
npm i @astrojs/prismpnpm i @astrojs/prismyarn add @astrojs/prism---import { Prism } from '@astrojs/prism';---<Prism lang="js" code={`const foo = 'bar';`} />这个组件通过应用 Prism 的 CSS 类为代码块提供特定语言的语法高亮。注意,你需要提供 Prism 的 CSS 样式表(或用自己的),以启用语法高亮!参见 Prism 配置部分了解更多细节。
参见 Prism 支持的语言列表,在那里你可以找到一种语言的对应别名。而且,你也可以用 lang="astro" 来展示 Astro 代码块!
<Image />
段落标题 <Image />---// 导入图像组件和图片import { Image } from 'astro:assets';import myImage from "../assets/my_image.png"; // Image is 1600x900---<!-- `alt` 在 Image 组件中是必需的属性 --><Image src={myImage} alt="A description of my image." /><!-- 输出 --><!-- Image 组件已经过优化,并且对应的属性也被强制使用。 --><img src="/_astro/my_image.hash.webp" width="1600" height="900" decoding="async" loading="lazy" alt="A description of my image."/>属性
段落标题 属性- src(必需的)
- alt(必需的)
- width 和 height(对
public/和远程图像而言是必需的) - format
- quality
- densities
- widths
除了上述属性之外,<Image /> 组件还接受 HTML <img> 标签接受的所有属性。
详见图像指南。
<Picture />
段落标题 <Picture />
添加于:
astro@3.3.0
使用内置的 <Picture /> Astro 组件来展示具有多种格式和(或)尺寸的响应式图像。
---import { Picture } from 'astro:assets';import myImage from "../assets/my_image.png"; // 图像的分辨率为 1600x900---<!-- 在图片组件上 `alt` 属性是必需的 --><Picture src={myImage} formats={['avif', 'webp']} alt="A description of my image." /><!-- 输出 --><picture> <source srcset="/_astro/my_image.hash.avif" type="image/avif" /> <source srcset="/_astro/my_image.hash.webp" type="image/webp" /> <img src="/_astro/my_image.hash.png" width="1600" height="900" decoding="async" loading="lazy" alt="A description of my image." /></picture>详见图像指南。
属性
段落标题 属性<Picture /> 接受 <Image /> 组件的所有属性,以及以下属性:
formats
段落标题 formats一个图像格式的数组,用于 <source> 标签。默认情况下,它被设置为 ['webp']。
fallbackFormat
段落标题 fallbackFormat用于作为 <img> 标签的回退值的格式。对于静态图像,默认为 .png;对于动画图像,默认为 .gif;对于 SVG 文件,默认为 .svg。
pictureAttributes
段落标题 pictureAttributes一个被添加到 <picture> 标签的属性对象。使用该属性可将属性应用于外部的 <picture> 元素本身。除了用于图像转换的属性外,直接应用于 <Picture /> 组件的属性将应用于内部的 <img> 元素。
<Content />
段落标题 <Content />一个通用组件,用于呈现 内容集合条目 的内容。
首先,使用 getCollection() 或 getEntry() 查询一个或多个条目。然后,entry.render() 函数可以返回 <Content /> 组件,以供在 .astro 文件模板中使用。
---import { getEntry } from 'astro:content';const entry = await getEntry('blog', 'post-1');const { Content } = await entry.render();---<p>Published on: {entry.data.published.toDateString()}</p><Content /><ViewTransitions />
段落标题 <ViewTransitions />在每个希望应用视图过渡动画的页面上,通过导入并将 <ViewTransitions /> 路由组件添加到 <head> 中,来选择使用单个页面上的视图过渡动画。
---import { ViewTransitions } from 'astro:transitions';---<html lang="en"> <head> <title>My Homepage</title> <ViewTransitions /> </head> <body> <h1>Welcome to my website!</h1> </body></html>查看更多关于如何控制路由器和向页面元素和组件添加过渡动画指令的信息。
<Debug />
段落标题 <Debug />---import { Debug } from 'astro:components';const serverObject = { a: 0, b: "string", c: { nested: "object" }}---<Debug {serverObject} />这个组件提供了无需 JavaScript 在客户端检查数值的方法。
Reference