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 文件使用 Astro.glob()
加载的 Markdown 文件返回以下 MarkdownInstance
接口:
export interface MarkdownInstance<T extends Record<string, any>> { /* 在此文件的 YAML frontmatter 中指定的任何数据 */ frontmatter: T; /* 该文件的文件绝对路径 */ file: string; /* 该文件的渲染路径 */ url: string | undefined; /* 渲染此文件内容的 Astro 组件 */ Content: AstroComponentFactory; /** (仅限 Markdown) Markdown 文件的原始内容,不包括布局 HTML 和 YAML frontmatter */ rawContent(): string; /* (仅限 Markdown) Markdown 文件编译后的 HTML,不包括布局 HTML */ compiledContent(): string; /* 返回该文件中 h1...h6 元素数组的函数 */ getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>; default: AstroComponentFactory;}
你可以选择使用 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: AstroComponentFactory;}
其他文件
段落标题 其他文件其他文件可能有各种不同的接口,但如果你不知道文件类型包含什么,那么 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.request类型:Request
Astro.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.response类型:ResponseInit & { readonly headers: Headers }
Astro.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类型:AstroCookies
astro@1.4.0
Astro.cookies
包含用于在服务端渲染模式下读取和操作 cookie 的工具方法。
get
段落标题 get类型:(key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined
获取 AstroCookie
对象形式的 cookie,该对象包含value
和用于将 cookie 转换为非字符串类型的工具方法。
has
段落标题 has类型:(key: string, options?: AstroCookieGetOptions) => boolean
用于判断 cookie 是否存在。如果这个 cookie 已经通过Astro.cookies.set()
设置,这将返回 true,否则它将检查 Astro.request
中的 cookies。
set
段落标题 set类型:(key: string, value: string | object, options?: AstroCookieSetOptions) => void
将 cookie key
设置为给定的值。这将试图把 cookie 的值转换为一个字符串。选项提供了设置 cookie 功能的方法,例如 maxAge
或 httpOnly
。
delete
段落标题 delete类型:(key: string, options?: AstroCookieDeleteOptions) => void
通过设置过去的到期日期(Unix 时间为 0)使 cookie 失效。
一旦 Cookie 被“删除”(过期),Astro.cookies.has()
将返回 false
,Astro.cookies.get()
将返回一个 value
为 undefined
的 AstroCookie
。删除 Cookie 时可用的选项包括:domain
、path
、httpOnly
、sameSite
和 secure
。
merge
段落标题 merge类型:(cookies: AstroCookies) => void
将新的 AstroCookies
实例合并到当前实例中。任何新的 cookie 将被添加到当前实例中,任何具有相同名称的 cookie 将覆盖现有值。
headers
段落标题 headers类型:() => Iterator<string>
获取将与响应一起发送的 Set-Cookie
的 header 的值。
AstroCookie
段落标题 AstroCookie通过 Astro.cookies.get()
获取 cookie 返回一个 AstroCookie
类型。它具有以下结构。
value
段落标题 value类型:string
cookie 的原始字符串值。
json
段落标题 json类型:() => Record<string, any>
通过 JSON.parse()
解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出异常。
number
段落标题 number类型:() => number
将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。
boolean
段落标题 boolean类型:() => boolean
转换 cookie 的值为 boolean 类型。
AstroCookieGetOptions
段落标题 AstroCookieGetOptions
添加于:
astro@4.1.0
获取 cookie 允许通过 AstroCookieGetOptions
接口指定选项:
decode
段落标题 decode类型:(value: string) => string
允许自定义如何将 cookie 反序列化为值。
AstroCookieSetOptions
段落标题 AstroCookieSetOptions
添加于:
astro@4.1.0
通过 Astro.cookies.set()
设置 cookie,允许传入 AstroCookieSetOptions
来自定义 cookie 如何被序列化。
domain
段落标题 domain类型:string
指定域。如果未设置域,则大多数客户端将解释为应用于当前域。
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()类型:(path: string, status?: number) => Response
允许你重定向到另一个页面,并可选地提供一个 HTTP 响应状态码 作为第二个参数。
页面(而不是子组件)必须 return
Astro.redirect()
的结果,以便重定向发生。
对于静态生成的网站,这将使用 <meta http-equiv="refresh">
标签 实现客户端重定向,并且不支持状态码。
使用按需渲染模式时,支持状态码。除非指定其他代码,否则 Astro 将以默认的 HTTP 302
响应状态码实现重定向请求。
以下示例将用户重定向到登录页面:
---import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// 如果用户未登录,则将其重定向到登录页面if (!isLoggedIn(cookie)) { return Astro.redirect('/login');}---
Astro.rewrite()
段落标题 Astro.rewrite()类型:(rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
允许你从不同的 URL 或路径提供内容,而不会将浏览器重定向到新页面。
该方法接受字符串、URL
或 Request
作为路径的位置。
使用字符串提供一个明确的路径:
---return Astro.rewrite("/login")---
当你需要构造重写的 URL 路径时,使用 URL
类型。以下示例通过从相对路径 "../"
创建一个新的 URL 来呈现页面的父路径:
---return Astro.rewrite(new URL("../", Astro.url))---
使用 Request
类型完全控制发送到新路径的 Request
。以下示例发送一个请求来渲染父页面,同时提供标头:
---return Astro.rewrite(new Request(new URL("../", Astro.url), { headers: { "x-custom-header": JSON.stringify(Astro.locals.someValue) }}))---
Astro.url
段落标题 Astro.url类型:URL
astro@1.0.0-rc
由当前 Astro.request.url
的链接字符串值构造的 URL对象。对于与请求链接的某些属性进行交互很有用,例如 pathname 和 origin。
相当于 new URL(Astro.request.url)
。
如果 site 未配置为静态站点或者使用 server
或 hybrid
输出的按需渲染站点,Astro.url
在开发模式下将是 localhost
。
<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类型:string
astro@1.0.0-rc
指定请求的 IP 地址。这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
---const ip = Astro.clientAddress;---
<div>你的 IP 地址是:<span class="address">{ ip }</span></div>
Astro.site
段落标题 Astro.site类型:URL | undefined
Astro.site
返回根据 Astro 配置中的 site
生成的 URL
。如果未定义 Astro 配置中的 site
,Astro.site
也不会被定义。
Astro.generator
段落标题 Astro.generator类型:string
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> -->
回调函数可以传递给带有 slot
属性并包装着 HTML 元素标签的具名插槽。这个元素仅用于将回调传递给具名插槽,而不会被渲染到页面上。
<Shout message="slots!"> <fragment slot="message"> {(message) => <div>{message}</div>} </fragment></Shout>
使用标准的 HTML 元素作为包装标签,或者使用任何小写标签(例如 <fragment>
而不是 <Fragment />
),这些标签不会被解释为组件。不要使用 HTML 的 <slot>
元素,因为它会被解释为 Astro 插槽。
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.locals
添加于:
astro@2.4.0
Astro.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.preferredLocale类型:string | undefined
astro@3.5.0
Astro.preferredLocale
是一个代表当前用户的首选语言环境的计算出的值。
它是通过检查 i18n.locales
数组中配置的语言环境和用户浏览器通过头部 Accept-Language
指定的语言环境来计算的。如果不存在匹配项则该值为 undefined
。
这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
Astro.preferredLocaleList
段落标题 Astro.preferredLocaleList类型:string[] | undefined
astro@3.5.0
Astro.preferredLocaleList
是一个同时被浏览器请求并且你的网站也支持的语言环境的数组。它是一个由你的网站和你的访客共同支持的语言环境的列表。
如果浏览器请求的语言环境没有在你的网站中被支持,那么该值为 []
:你不支持你的访客的任何首选语言环境。
如果浏览器没有指定任何首选语言环境,那么该值将是 i18n.locales
:你支持的所有语言环境都将被同等视为访客倾向的语言环境。
这个属性只在为 SSR(服务器端渲染)构建时可用,不应该用于静态网站。
Astro.currentLocale
段落标题 Astro.currentLocale类型:string | undefined
astro@3.5.6
从当前 URL 使用你的 locales
配置中指定的语法计算出的语言环境。如果 URL 不包含 /[locale]/
前缀,则该值将默认为 i18n.defaultLocale
。
Astro.getActionResult()
段落标题 Astro.getActionResult()类型:(action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
Astro.getActionResult()
是一个返回 Action 提交结果的函数。它接受一个 Action 函数作为参数(例如 actions.logout
),当接收到提交时返回一个 data
或 error
对象。否则,它将返回 undefined
。
---import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.logout);---
<form action={actions.logout}> <button type="submit">退出登录</button></form>{result?.error && <p>退出登录失败。请再试一次。</p>}
Astro.callAction()
段落标题 Astro.callAction()
添加于:
astro@4.15.0
Astro.callAction()
是一个直接从你的 Astro 组件中调用 Action 处理程序的函数。它接受一个 Action 函数作为第一个参数(例如 actions.logout
),以及该 Action 接收的任何输入作为第二个参数。它返回 Action 的结果作为 Promise。
---import { actions } from 'astro:actions';
const { data, error } = await Astro.callAction(actions.logout, { userId: '123' });---
端点上下文
段落标题 端点上下文端点函数接收一个上下文对象作为第一个参数。它与许多 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.props
添加于:
astro@1.5.0
context.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
一个标准的 Request 对象。它可以用来获取请求的 url
、headers
、method
甚至是 body
。
import type { APIContext } from 'astro';
export function GET({ request }: APIContext) { return new Response(`Hello ${request.url}`);}
context.cookies
段落标题 context.cookies类型:AstroCookies
context.cookies
包含用于读取和操作 cookie 的工具。
context.url
段落标题 context.url类型:URL
astro@1.5.0
context.url
是一个 URL 对象,它是从当前 context.request.url
URL 字符串值构造的。
另见:Astro.url
context.clientAddress
段落标题 context.clientAddress类型:string
astro@1.5.0
指定请求的 IP 地址。此属性仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。
import type { APIContext } from 'astro';
export function GET({ clientAddress }: APIContext) { return new Response(`Your IP address is: ${clientAddress}`);}
context.site
段落标题 context.site类型:URL | undefined
astro@1.5.0
context.site
返回一个由 Astro 配置中的 site
生成的 URL
。如果未定义,则将返回从 localhost
生成的 URL。
另见:Astro.site
context.generator
段落标题 context.generator类型:string
astro@1.5.0
context.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()类型:(path: string, status?: number) => Response
astro@1.5.0
context.redirect()
返回一个 Response 对象,允许你重定向到另一个页面。此函数仅在构建 SSR(服务器端渲染)时可用,不应用于静态站点。
import type { APIContext } from 'astro';
export function GET({ redirect }: APIContext) { return redirect('/login', 302);}
context.rewrite()
段落标题 context.rewrite()类型:(rewritePayload: string | URL | Request) => Promise<Response>
astro@4.13.0
允许你从不同的 URL 或路径提供内容,而不会将浏览器重定向到新页面。
该方法接受字符串、URL
或 Request
作为路径的位置。
使用字符串提供一个明确的路径:
import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) { return rewrite('/login');}
当你需要构造重写的 URL 路径时,使用 URL
类型。以下示例通过从相对路径 "../"
创建一个新的 URL 来呈现页面的父路径:
import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) { return rewrite(new URL("../", Astro.url));}
使用 Request
类型完全控制发送到新路径的 Request
。以下示例发送一个请求来渲染父页面,同时提供标头:
import type { APIContext } from 'astro';
export function GET({ rewrite }: APIContext) { return rewrite(new Request(new URL("../", Astro.url), { headers: { "x-custom-header": JSON.stringify(Astro.locals.someValue) } }));}
context.locals
段落标题 context.locals
添加于:
astro@2.4.0
context.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
context.getActionResult()
段落标题 context.getActionResult()类型: (action: TAction) => ActionReturnType<TAction> | undefined
astro@4.15.0
context.getActionResult()
是一个函数,用于从你的 Astro 组件中返回 Action 提交结果。它接受一个 Action 函数作为参数(例如 actions.logout
),当接收到提交时返回一个 data
或 error
对象。否则,它将返回 undefined
。
context.callAction()
段落标题 context.callAction()
添加于:
astro@4.15.0
context.callAction()
是一个直接从你的 Astro 组件中调用 Action 处理程序的函数。它接受一个 Action 函数作为第一个参数(例如 actions.logout
),以及该 Action 接收的任何输入作为第二个参数。它返回 Action 的结果作为 Promise。
getStaticPaths()
段落标题 getStaticPaths()类型:(options: GetStaticPathsOptions) => Promise<GetStaticPathsResult> | GetStaticPathsResult
如果页面在文件名中使用动态参数,该组件将需要导出一个 getStaticPaths()
函数。
必须要有该函数,因为 Astro 是静态站点生成器。这意味着整个网站是预构建的。如果 Astro 不知道在构建时生成什么页面,你的用户在访问你的网站时就看不到它。
---export async function getStaticPaths() { return [ { params: { /* 必需 */ }, props: { /* 可选 */ } }, { params: { ... } }, { params: { ... } }, // ... ];}---<!-- 你的 HTML 模板在这里 -->
getStaticPaths()
函数应该返回对象数组,以确定哪些路径会被 Astro 预渲染。
使用 TypeScript 时,请使用 GetStaticPaths
类型工具来确保对 params
和 props
进行类型安全的获取。
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()
函数具有以下参数:
data
- 数组,包含了传递给paginate()
函数的页面数据片段options
- 具有以下属性的可选对象:pageSize
- 每页显示的项目数(默认为10
)params
- 用于创建动态路由的附加参数props
- 在每个页面上可用的附加属性
paginate()
:假定文件名为 [page].astro
或 [...page].astro
。page
参数将是链接中的页数。
/posts/[page].astro
:会产生/posts/1
、/posts/2
、/posts/3
等链接。/posts/[...page].astro
:将产生/posts
、/posts/2
/posts/3
等链接。
page
分页参数
段落标题 page 分页参数类型: Page<TData>
分页会给每个渲染的页面传递 page
参数,代表分页集合中的单页数据。这包括你分页的数据(page.data
)以及该页的元数据(page.url
、page.start
、page.end
、page.total
等)。这些元数据对诸如“下一页”按钮或“显示 100 个中前十个”的信息很有用。
page.data
段落标题 page.data类型: Array<TData>
从 paginate()
函数中返回当前页面数据的数组。
page.start
段落标题 page.start类型:number
当前页第一个项目的索引,从 0
开始(例如,如果 pageSize: 25
,第一页该值未 0
,第二页为25
,以此类推)。
page.end
段落标题 page.end类型:number
当前页面最后一条数据的索引。
page.size
段落标题 page.size类型:number
默认值:10
每个页面有多少条数据。
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
)。如果为 base
设置了值,那么需要将 base 路径拼接到链接前面。
page.url.next
段落标题 page.url.next类型:string | undefined
获取下一页链接(如果没有更多的页面,将是undefined
)。如果为 base
设置了值,那么需要将 base 路径拼接到链接前面。
page.url.first
段落标题 page.url.first类型:string | undefined
astro@4.12.0
获取第一页链接(如果在首页,将是undefined
)。 如果为 base
设置了值,那么需要将 base 路径拼接到链接前面。
page.url.last
段落标题 page.url.last类型:string | undefined
astro@4.12.0
获取最后一页链接(如果在最后一页,将是undefined
)。如果为 base
设置了值,那么需要将 base 路径拼接到链接前面。
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()类型:(options: UnresolvedImageTransform) => Promise<GetImageResult>
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>
它返回了一个具有以下类型的对象:
type GetImageResult = { /* 渲染图像所需的附加 HTML 属性(宽度、高度、样式等) */ attributes: Record<string, any>; /* 已通过校验的参数 */ options: ImageTransform; /* 传递的原始参数 */ rawOptions: ImageTransform; /* 生成图像的路径 */ src: string; srcSet: { /* 为 srcset 生成值,每个条目都有一个 url 和一个 size */ values: SrcSetValue[]; /* 准备在`srcset`属性中使用的值 */ attribute: string; };}
内容集合(astro:content
)
段落标题 内容集合(astro:content)
添加于:
astro@2.0.0
内容集合提供了 API 来配置和查询 src/content/
中的 Markdown 或 MDX 文档。有关功能和用法示例,请参考内容集合指南。
defineCollection()
段落标题 defineCollection()类型:(input: CollectionConfig) => CollectionConfig
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类型:'content' | 'data'
默认:'content'
astro@2.5.0
type
是一个字符串,用于定义存储在集合中的条目的类型:
'content'
- 用于内容创作格式,如 Markdown (.md
)、MDX (.mdx
) 或 Markdoc (.mdoc
)'data'
- 用于 JSON (.json
) 或 YAML (.yaml
) 等纯数据格式
这意味着集合不能存储内容和数据格式的混合。你必须按类型将这些条目分割成单独的集合。
schema
段落标题 schema类型:ZodType | (context: SchemaContext) => ZodType
schema
是一个可选的 Zod 对象,用于配置集合的文档 frontmatter 的类型和形状。每个值必须使用 Zod 验证器
有关示例请参考 内容集合
指南
reference()
段落标题 reference()类型:(collection: string) => ZodEffects<ZodString, { collection, id: string } | { collection, slug: string }>
astro@2.5.0
在内容配置中使用 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<TCollectionName>) => boolean) => CollectionEntry<TCollectionName>[]
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
类型:
(collection: string, contentSlugOrDataId: string) => CollectionEntry<TCollectionName>
({ collection: string, id: string }) => CollectionEntry<TCollectionName>
({ collection: string, slug: string }) => CollectionEntry<TCollectionName>
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
类型:
(Array<{ collection: string, id: string }>) => CollectionEntry<TCollectionName>[]
(Array<{ collection: string, slug: string }>) => CollectionEntry<TCollectionName>[]
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) => Promise<CollectionEntry<TCollectionName>>
使用 getEntry()
函数 查询内容条目。该函数接受与 getEntryBySlug()
相同的参数,并支持通过 id
查询 JSON 或 YAML 集合。
getEntryBySlug()
是一个函数,用于通过集合名称和条目 slug
检索单个集合条目。
---import { getEntryBySlug } from 'astro:content';
const enterprise = await getEntryBySlug('blog', 'enterprise');---
有关示例请参考 内容集合
指南 以获取示例用法。
getDataEntryById()
段落标题 getDataEntryById()类型: (collection: string, id: string) => Promise<CollectionEntry<TCollectionName>>
astro@2.5.0
使用 getEntry()
函数 查询数据条目。该函数接受与 getDataEntryById()
相同的参数,并支持通过 slug
查询 Markdown 等内容创作格式的条目。
getDataEntryById()
是一个用于通过集合名称和条目 id
检索单个集合条目的函数。
---import { getDataEntryById } from 'astro:content';const picardProfile = await getDataEntryById('captains', 'picard');---
集合条目类型
段落标题 集合条目类型getCollection()
和 getEntryBySlug()
函数都会返回 CollectionEntry
类型的条目。这个类型可以从 astro:content
中获取:
import type { CollectionEntry } from 'astro:content';
CollectionEntry<TCollectionName>
类型是一个对象,具有以下值。 TCollectionName
是你正在查询的集合的名称(例如 CollectionEntry<'blog'>
)。
id
段落标题 id适用于: type: 'content'
and type: 'data'
集合
示例类型:
- 内容集合:
'entry-1.md' | 'entry-2.md' | ...
- 数据集合:
'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
添加于:
astro@3.1.0
这是一个在 src/content/config.*
文件中定义的所有集合名称的字符串联合类型。当定义一个可以接受任何集合名称的通用函数时,这个类型很有用。
import type { CollectionKey, getCollection } from 'astro:content';
async function getCollection(collection: CollectionKey) { return getCollection(collection);}
ContentCollectionKey
段落标题 ContentCollectionKey
添加于:
astro@3.1.0
一个在 src/content/config.*
文件中定义的所有 type: 'content'
集合名称的字符串联合类型。
DataCollectionKey
段落标题 DataCollectionKey
添加于:
astro@3.1.0
一个在 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()类型:(context: APIContext, next: MiddlewareNext) => Promise<Response> | Response | Promise<void> | void
一个在 src/middleware.js
里的必须导出的函数,它将在每次渲染页面或端点时被调用。它接受两个参数:context 和 next()。onRequest()
必须返回一个 Response
:要么直接返回,要么通过调用 next()
返回。
export function onRequest (context, next) { // 拦截一个请求的响应数据 // 可选修改响应 // 直接返回一个 Response 对象,或者调用 `next()` 的结果 return next();};
context
段落标题 context类型:APIContext
onRequest()
的第一个参数是一个上下文对象。它反映了许多 Astro
全局属性。
next()
段落标题 next()类型:(rewritePayload?: string | URL | Request) => Promise<Response>
onRequest()
的第二个参数是一个调用链中的所有后续中间件,并返回一个 Response
的函数。例如,其他中间件可以修改响应的 HTML 主体,等待 next()
的结果将允许你的中间件响应这些更改。
自从 Astro v4.13.0,next()
接受一个可选的 URL 路径参数,形式为字符串、URL
或 Request
,用于重写当前请求而不重新触发新的渲染阶段。
sequence()
段落标题 sequence()类型:(...handlers: MiddlewareHandler[]) => MiddlewareHandler
一个接受中间件函数作为参数的函数,它将按照它们传递的顺序执行它们。
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()类型:(context: CreateContext) => APIContext
astro@2.8.0
一个底层 API,用于创建一个 APIContext
以传递给 Astro 中间件的 onRequest()
函数。
此函数可以由集成/适配器用于执行 Astro 中间件。
trySerializeLocals()
段落标题 trySerializeLocals()类型:(value: unknown) => string
astro@2.8.0
一个底层 API,它接受任何值并尝试返回它的序列化版本(一个字符串)。如果该值无法序列化,该函数将抛出一个运行时错误。
国际化(astro:i18n
)
段落标题 国际化(astro:i18n)
添加于:
astro@3.5.0
此模块提供了一些函数,帮助你使用项目配置的语言环境设置创建 URL。
使用 i18n 路由为你的项目创建路由将依赖于你设置的某些配置值,这些值会影响你的页面路由。使用这些函数创建路由时,请确保考虑到你的个人设置,包括:
另外,请注意,这些函数为你的 defaultLocale
创建的返回 URL 将反映你的 i18n.routing
配置。
有关功能和使用示例,请参阅我们的 i18n 路由指南。
getRelativeLocaleUrl()
段落标题 getRelativeLocaleUrl()类型:(locale: string, path?: string, options?: GetLocaleOptions) => string
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()类型:(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()类型:(path?: string, options?: GetLocaleOptions) => string[]
像使用 getRelativeLocaleUrl
那样使用此函数,返回所有语言环境的相对路径列表。
getAbsoluteLocaleUrlList()
段落标题 getAbsoluteLocaleUrlList()类型:(path?: string, options?: GetLocaleOptions) => string[]
像使用 getAbsoluteLocaleUrl
那样使用此函数,返回所有语言环境的绝对路径列表。
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()
段落标题 getLocaleByPath()类型:(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()类型:(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()类型:(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()类型:(context: APIContext, response?: Response) => Promise<Response> | undefined
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()类型:(options: { prefixDefaultLocale: boolean, redirectToDefaultLocale: boolean }) => MiddlewareHandler
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()类型:(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 });})
视图过渡客户端 API (astro:transitions/client
)
段落标题 视图过渡客户端 API (astro:transitions/client)
添加于:
astro@3.2.0
此模块提供了一些函数,用于控制和与视图过渡 API 和客户端路由进行交互。
对于功能和使用示例,请参阅我们的视图过渡指南。
navigate()
段落标题 navigate()类型:(href: string, options?: Options) => void
astro@3.2.0
一个使用视图过渡 API 导航到给定 href
的函数。
此函数签名基于 浏览器 Navigation API 中的 navigate
函数。虽然基于 Navigation API,但此函数是在 History API 之上实现的,以允许在不重新加载页面的情况下进行导航。
history
选项
段落标题 history 选项类型:'auto' | 'push' | 'replace'
默认值:'auto'
astro@3.2.0
定义了如何将此导航添加到浏览器历史记录中。
'push'
:路由将使用history.pushState
在浏览器历史记录中创建一个新条目。'replace'
:路由将使用history.replaceState
更新 URL,而不会在导航中添加新条目。'auto'
(默认):路由将尝试history.pushState
,但如果无法进行过渡,则当前 URL 将保持不变,浏览器历史记录不会发生变化。
此选项遵循浏览器 Navigation API 中的 history
选项,但简化了在 Astro 项目中可能发生的情况。
formData
选项
段落标题 formData 选项类型:FormData
astro@3.5.0
一个 FormData
对象,用于 POST
请求。
当提供此选项时,导航目标页面的请求将以 POST
请求的形式发送,内容为表单数据对象。
当提交一个带有视图过渡的 HTML 表单时,将使用此方法代替默认的页面重新加载导航。调用此方法允许以编程方式触发相同的行为。
info
选项
段落标题 info 选项类型:any
astro@3.6.0
与导航相关的 astro:before-preparation
和 astro:before-swap
事件中包含的任意数据。
此选项模仿了浏览器 Navigation API 中的 info
选项。
state
选项
段落标题 state 选项类型:any
astro@3.6.0
与导航相关的 NavitationHistoryEntry
对象中关联的任意数据。此数据可以通过 history.getState
函数 从 History API 中检索。
此选项模仿了浏览器 Navigation API 中的 state
选项。
sourceElement
选项
段落标题 sourceElement 选项类型:Element
astro@3.6.0
此导航的触发元素,如果有的话。此元素将在以下事件中可用:
astro:before-preparation
astro:before-swap
supportsViewTransitions
段落标题 supportsViewTransitions类型:boolean
astro@3.2.0
当前浏览器是否支持并启用视图过渡。
transitionEnabledOnThisPage
段落标题 transitionEnabledOnThisPage类型:boolean
astro@3.2.0
当前页面是否启用了视图过渡以进行客户端导航。这可以用于使组件在视图过渡页面上的行为有所不同。
getFallback
段落标题 getFallback类型:() => 'none' | 'animate' | 'swap'
astro@3.6.0
返回在浏览器不支持视图过渡时使用的回退策略。
有关如何选择和配置回退行为的详细信息,请参阅 回退控制 指南。
astro:before-preparation
事件
段落标题 astro:before-preparation 事件在视图过渡中导航开始时触发的事件。此事件发生在任何请求之前,并且不会更改任何浏览器状态。
此事件具有以下属性:
有关如何使用此事件的详细信息,请参阅 视图过渡指南.
astro:after-preparation
事件
段落标题 astro:after-preparation 事件使用视图过渡加载导航中的下一个页面后触发的事件。
此事件没有属性。
有关如何使用此事件的详细信息,请参阅 视图过渡指南.
astro:before-swap
事件
段落标题 astro:before-swap 事件在视图过渡中导航的下一个页面解析、准备并链接到 document 后,但在任何内容在 document 之间交换之前触发的事件。
此事件不能取消。调用 preventDefault()
是无效的。
此事件具有以下属性:
有关如何使用此事件的详细信息,请参阅 视图过渡指南.
astro:after-swap
事件
段落标题 astro:after-swap 事件在视图过渡中导航的下一个页面内容交换后,但在视图过渡结束之前触发的事件。
在触发此事件时,历史记录条目和滚动位置已经更新。
astro:page-load
事件
段落标题 astro:page-load 事件在页面完成加载后触发的事件,无论是通过视图过渡导航还是浏览器原生导航。
当视图过渡在页面上启用时,通常在 DOMContentLoaded
上执行的代码应更改为在此事件上执行。
视图过渡事件属性
段落标题 视图过渡事件属性
添加于:
astro@3.6.0
info
段落标题 info类型:URL
在导航期间定义的任意数据。
这是在 navigate()
函数 的 info
选项 中传递的文字值。
sourceElement
段落标题 sourceElement类型:Element | undefined
触发导航的元素。例如,这可以是点击的 <a>
元素。
当使用 navigate()
函数 时,这将是调用中指定的元素。
newDocument
段落标题 newDocument类型:Document
导航中下一个页面的 document。此 document 的内容将替换当前 document 的内容。
navigationType
段落标题 navigationType类型:'push' | 'replace' | 'traverse'
正在发生的导航类型。
push
: 正在为新页面创建一个新的NavigationHistoryEntry
。replace
: 当前的NavigationHistoryEntry
正在被新页面的条目替换。traverse
: 没有创建NavigationHistoryEntry
。历史记录中的位置正在改变。 遍历的方向由direction
属性 给出
direction
段落标题 direction类型:Direction
过渡的方向。
forward
: 在历史记录中导航到下一个页面或新页面。back
: 在历史记录中导航到前一个页面。- 其他监听器可能设置的任何其他内容。
from
段落标题 from类型:URL
正在导航的页面的 URL。
to
段落标题 to类型:URL
正在导航的页面的 URL。此属性可以修改,在生命周期结束时使用的值将是下一个页面的 NavigationHistoryEntry
的值。
formData
段落标题 formData类型:FormData | undefined
一个用于 POST
请求的 FormData
对象。
当此属性设置时,将使用给定的表单数据对象作为内容发送 POST
请求到 to
URL,而不是正常的 GET
请求。
当提交一个带有视图过渡的 HTML 表单时,此字段会自动设置为表单中的数据。当使用 navigate()
函数 时,此值与给定的选项相同。
loader
段落标题 loader类型:() => Promise<void>
在导航过程中下个阶段的实现(加载下一个页面)。此实现可以覆盖以添加额外的行为。
viewTransition
段落标题 viewTransition在导航过程中使用的视图过渡对象。在浏览器不支持 视图过渡 API 的情况下,这是一个对象,实现了相同的 API 以方便使用,但没有 DOM 集成。
swap
段落标题 swap类型:() => void
document 交换逻辑的实现。
有关如何构建自定义交换函数的详细信息,请参阅 视图过渡指南.
默认情况下,此实现将按顺序调用以下函数:
deselectScripts()
段落标题 deselectScripts()类型:(newDocument: Document) => void
标记在新的 document 中不应执行的脚本。这些脚本已经在当前 document 中,并且没有使用 data-astro-rerun
标记为重新执行。
swapRootAttributes()
段落标题 swapRootAttributes()类型:(newDocument: Document) => void
在 document 根节点之间交换属性,如 lang
属性。这也包括 Astro 注入的内部属性,如 data-astro-transition
,这使得过渡方向可用于 Astro 生成的 CSS 规则。
在构建自定义交换函数时,重要的是调用此函数,以避免破坏视图过渡的动画。
swapHeadElements()
段落标题 swapHeadElements()类型:(newDocument: Document) => void
从当前 document 的 <head>
中删除所有未持久化到新 document 的元素。然后将新 document 的 <head>
中的所有新元素附加到当前 document 的 <head>
。
saveFocus()
段落标题 saveFocus()类型:() => () => void
在当前页面上存储聚焦的元素,并返回一个函数,当调用时,如果聚焦的元素被持久化,则将焦点返回给该元素。
swapBodyElements()
段落标题 swapBodyElements()类型:(newBody: Element, oldBody: Element) => void
用新 document 的 body 替换旧的 body。然后,遍历旧 body 中应持久化的每个元素,并在新 body 中找到匹配的元素,将旧元素交换回原位。
Actions (astro:actions
)
段落标题 Actions (astro:actions)
添加于:
astro@4.15.0
Action 帮助你构建一个类型安全的后端,你可以从客户端代码和 HTML 表单中调用它。所有用于定义和调用 Action 的工具函数都由 astro:actions
模块暴露。有关示例和使用说明,请参阅 Actions 指南。
defineAction()
段落标题 defineAction()
添加于:
astro@4.15.0
defineAction()
函数接受一个 handler()
函数,其中包含在调用 Action 时要运行的服务器逻辑,以及一个可选的 input
属性,用于在运行时验证输入参数。
export const server = { getGreeting: defineAction({ input: z.object({ name: z.string(), }), handler: async (input, context) => { return `Hello, ${input.name}!` } })}
handler()
属性
段落标题 handler() 属性类型:(input, context) => any
defineAction()
函数接受一个 handler()
函数,其中包含在调用 Action 时要运行的服务器逻辑。此函数可以返回数据,这些数据将自动序列化并发送给调用者。
handler()
函数被调用时,接受用户输入作为其第一个参数。如果设置了 input
验证器,那么用户输入将在传递给 handler()
前进行验证。第二个参数是一个 context
对象,包含大多数 Astro 的 标准端点上下文,不包括 getActionResult()
, callAction()
, 和 redirect()
。
返回值使用 devalue 库 进行解析。它支持 JSON 值,以及 Date()
, Map()
, Set()
, 或 URL()
的实例。
input
验证器
段落标题 input 验证器类型:ZodType | undefined
可选的 input
属性接受一个 Zod 验证器,用于在运行时验证处理程序的输入。如果 action 验证失败,将返回 BAD_REQUEST
错误 并跳过 handler
。
如果省略 input
,则 handler
将接收 JSON 请求的 unknown
类型的输入,以及表单请求的 FormData
类型。
与 accept: 'form'
一起使用
段落标题 与 accept: 'form' 一起使用如果你的 action 接受表单输入,请使用 z.object()
验证器将表单数据自动解析为类型化对象。表单数据字段支持以下验证器:
- 使用
z.number()
验证类型为number
的输入 - 使用
z.boolean()
验证类型为checkbox
的输入 - 使用
z.instanceof(File)
验证类型为file
的输入 - 使用
z.array(/* validator */)
验证相同name
的多个输入 - 使用
z.string()
验证所有其他输入
z.object()
验证器还支持包括 .refine()
, .transform()
, 和 .pipe()
在内的扩展函数。
要搭配应用不同验证器的组合,请使用 z.discriminatedUnion()
包装器,它根据表单的特定字段以缩小类型范围。此示例通过接受表单提交以判断是 “创建(create)” 或是 “更新(update)” 了一名用户信息,判断时使用表单域的 type
属性字段来确定要验证的对象:
import { defineAction } from 'astro:actions';import { z } from 'astro:schema';
export const server = { changeUser: defineAction({ accept: 'form', input: z.discriminatedUnion('type', [ z.object({ // 当 `type` 字段中的值含有 `create` 时匹配 type: z.literal('create'), name: z.string(), email: z.string().email(), }), z.object({ // 当 `type` 字段中的值含有 `update` 时匹配 type: z.literal('update'), id: z.number(), name: z.string(), email: z.string().email(), }), ]), async handler(input) { if (input.type === 'create') { // input 为 { type: 'create', name: string, email: string } } else { // input 为 { type: 'update', id: number, name: string, email: string } } }, }),};
isInputError()
段落标题 isInputError()类型:(error?: unknown | ActionError) => boolean
astro@4.15.0
isInputError()
函数常用于检查 ActionError
是否是输入验证错误。当 input
验证器是 z.object()
时,输入错误包括一个 fields
对象,其中错误消息按名称分组。
更多关于使用 isInputError()
的信息,请参见 表单输入错误指南。
ActionError
段落标题 ActionError
添加于:
astro@4.15.0
ActionError
构造函数常用于在 handler()
函数中抛出错误。它接受一个 code
属性,描述发生的错误(例如:"UNAUTHORIZED"
),以及一个可选的 message
属性,提供进一步的细节。
code
段落标题 code
添加于:
astro@4.15.0
code
属性接受所有 HTTP 状态码的人类可读版本。以下是支持的 code:
BAD_REQUEST
(400): 客户端发送了无效的输入。当 actioninput
验证器验证失败时会抛出此错误。UNAUTHORIZED
(401): 客户端缺乏有效的身份验证凭据。FORBIDDEN
(403): 客户端无权访问资源。NOT_FOUND
(404): 服务器找不到请求的资源。METHOD_NOT_SUPPORTED
(405): 服务器不支持请求的方法。TIMEOUT
(408): 服务器在处理请求时超时。CONFLICT
(409): 服务器无法更新资源,因为存在冲突。PRECONDITION_FAILED
(412): 服务器不满足请求的前提条件。PAYLOAD_TOO_LARGE
(413): 服务器无法处理请求,因为负载过大。UNSUPPORTED_MEDIA_TYPE
(415): 服务器不支持请求的媒体类型。注意:Actions 已经检查了 JSON 和表单请求的Content-Type
标头,所以你可能不需要手动引发此代码。UNPROCESSABLE_CONTENT
(422): 服务器无法处理请求,因为存在语义错误。TOO_MANY_REQUESTS
(429): 服务器已超出指定的速率限制。CLIENT_CLOSED_REQUEST
(499): 客户端在服务器响应之前关闭了请求。INTERNAL_SERVER_ERROR
(500): 服务器意外失败。NOT_IMPLEMENTED
(501): 服务器不支持请求的功能。BAD_GATEWAY
(502): 服务器从上游服务器接收到无效响应。SERVICE_UNAVAILABLE
(503): 服务器暂时不可用。GATEWAY_TIMEOUT
(504): 服务器从上游服务器接收到超时。
message
段落标题 message
添加于:
astro@4.15.0
message
属性接受一个字符串。(例如:“用户必须登录。“)