Skip to content

Astro 渲染上下文

渲染页面时,Astro 提供特定于当前渲染的运行时 API。这包括有用的信息,例如当前页面 URL 以及执行操作(例如重定向到另一个页面)的 API。

¥When rendering a page, Astro provides a runtime API specific to the current render. This includes useful information such as the current page URL as well as APIs to perform actions like redirecting to another page.

.astro 组件中,此上下文可从 Astro 全局对象中获得。端点函数也使用相同的上下文对象作为其第一个参数来调用,其属性反映了 Astro 全局属性。

¥In .astro components, this context is available from the Astro global object. Endpoint functions are also called with this same context object as their first argument, whose properties mirror the Astro global properties.

某些属性仅适用于按需渲染的路由,或者在预渲染的页面上可能具有有限的功能。

¥Some properties are only available for routes rendered on demand or may have limited functionality on prerendered pages.

Astro 全局对象可用于所有 .astro 文件。使用 端点函数 中的 context 对象提供静态或实时服务器端点,在 中间件 中使用 context 对象在即将渲染页面或端点时注入行为。

¥The Astro global object is available to all .astro files. Use the context object in endpoint functions to serve static or live server endpoints and in middleware to inject behavior when a page or endpoint is about to be rendered.

¥The context object

以下属性在 Astro 全局变量(例如 Astro.propsAstro.redirect())上可用,在传递给端点函数和中间件的上下文对象(例如 context.propscontext.redirect())上也可用。

¥The following properties are available on the Astro global (e.g. Astro.props, Astro.redirect()) and are also available on the context object (e.g. context.props, context.redirect()) passed to endpoint functions and middleware.

props 是一个对象,包含已作为 组件属性 传递的任何值。

¥props is an object containing any values that have been passed as component attributes.

src/components/Heading.astro
---
const { title, date } = Astro.props;
---
<div>
<h1>{title}</h1>
<p>{date}</p>
</div>
src/pages/index.astro
---
import Heading from '../components/Heading.astro';
---
<Heading title="My First Post" date="09 Aug 2022" />
Learn more about how Markdown and MDX layouts handle props.

props 对象还包含渲染静态路由时从 getStaticPaths() 传递的任何 props

¥The props object also contains any props passed from getStaticPaths() when rendering static routes.

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' }, props: { author: 'Blu' } },
{ params: { id: '2' }, props: { author: 'Erika' } },
{ params: { id: '3' }, props: { author: 'Matthew' } }
];
}
const { id } = Astro.params;
const { author } = Astro.props;
---

也可以看看:使用 props 传递数据

¥See also: Data Passing with props

params 是一个对象,包含与请求匹配的动态路由段的值。它的键必须与页面或端点文件路径中的 参数 匹配。

¥params is an object containing the values of dynamic route segments matched for a request. Its keys must match the parameters in the page or endpoint file path.

在静态构建中,这将是 getStaticPaths() 返回的用于预渲染 动态路由params

¥In static builds, this will be the params returned by getStaticPaths() used for prerendering dynamic routes:

src/pages/posts/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: '1' } },
{ params: { id: '2' } },
{ params: { id: '3' } }
];
}
const { id } = Astro.params;
---
<h1>{id}</h1>

当按需渲染路由时,params 可以是与动态路由模式中的路径段匹配的任何值。

¥When routes are rendered on demand, params can be any value matching the path segments in the dynamic route pattern.

src/pages/posts/[id].astro
---
import { getPost } from '../api';
const post = await getPost(Astro.params.id);
// No posts found with this ID
if (!post) {
return Astro.redirect("/404")
}
---
<html>
<h1>{post.name}</h1>
</html>

也可以看看:params

¥See also: params

类型:URL

¥Type: URL

Added in: astro@1.0.0

url 是根据当前 request.url 值构造的 URL 对象。它对于与请求 URL 的各个属性(如路径名和来源)进行交互非常有用。

¥url is a URL object constructed from the current request.url value. It is useful for interacting with individual properties of the request URL, like pathname and origin.

Astro.url 相当于执行 new URL(Astro.request.url)

¥Astro.url is equivalent to doing new URL(Astro.request.url).

在开发模式下,url 将是 localhost URL。构建站点时,预渲染的路由将根据 sitebase 选项接收 URL。如果未配置 site,预渲染的页面也将在构建期间收到 localhost URL。

¥url will be a localhost URL in dev mode. When building a site, prerendered routes will receive a URL based on the site and base options. If site is not configured, prerendered pages will receive a localhost URL during builds as well.

src/pages/index.astro
<h1>The current URL is: {Astro.url}</h1>
<h1>The current URL pathname is: {Astro.url.pathname}</h1>
<h1>The current URL origin is: {Astro.url.origin}</h1>

你还可以使用 url 通过将其作为参数传递给 new URL() 来创建新的 URL。

¥You can also use url to create new URLs by passing it as an argument to new URL().

src/pages/index.astro
---
// Example: Construct a canonical URL using your production domain
const canonicalURL = new URL(Astro.url.pathname, Astro.site);
// Example: Construct a URL for SEO meta tags using your current domain
const socialImageURL = new URL('/images/preview.png', Astro.url);
---
<link rel="canonical" href={canonicalURL} />
<meta property="og:image" content={socialImageURL} />

类型:URL | undefined

¥Type: URL | undefined

site 返回由 Astro 配置中的 site 组成的 URL。如果你没有在 Astro 配置中为 site 设置值,它将返回 undefined

¥site returns a URL made from site in your Astro config. It returns undefined if you have not set a value for site in your Astro config.

src/pages/index.astro
<link
rel="alternate"
type="application/rss+xml"
title="Your Site's Title"
href={new URL("rss.xml", Astro.site)}
/>

类型:string

¥Type: string

Added in: astro@1.0.0

clientAddress 指定请求的 IP 地址。此属性仅适用于按需渲染的路由,不能在预渲染的页面上使用。

¥clientAddress specifies the IP address of the request. This property is only available for routes rendered on demand and cannot be used on prerendered pages.

src/pages/ip-address.astro
---
export const prerender = false; // Not needed in 'server' mode
---
<div>Your IP address is: <span class="address">{Astro.clientAddress}</span></div>

类型:boolean

¥Type: boolean

Added in: astro@5.0.0

表示当前页面是否预渲染的布尔值。

¥A boolean representing whether or not the current page is prerendered.

例如,你可以使用此属性在中间件中运行条件逻辑,以避免访问预渲染页面中的标头。

¥You can use this property to run conditional logic in middleware, for example, to avoid accessing headers in prerendered pages.

类型:string

¥Type: string

Added in: astro@1.0.0

generator 提供项目正在运行的 Astro 的当前版本。这是使用当前版本的 Astro 添加 <meta name="generator"> 标签的便捷方法。它遵循格式 "Astro v5.x.x"

¥generator provides the current version of Astro your project is running. This is a convenient way to add a <meta name="generator"> tag with your current version of Astro. It follows the format "Astro v5.x.x".

src/pages/site-info.astro
<html>
<head>
<meta name="generator" content={Astro.generator} />
</head>
<body>
<footer>
<p>Built with <a href="https://astro.build">{Astro.generator}</a></p>
</footer>
</body>
</html>

类型:Request

¥Type: Request

request 是标准 要求 对象。它可用于获取 urlheadersmethod,甚至请求的主体。

¥request is a standard Request object. It can be used to get the url, headers, method, and even the body of the request.

src/pages/index.astro
<p>Received a {Astro.request.method} request to "{Astro.request.url}".</p>
<p>Received request headers:</p>
<p><code>{JSON.stringify(Object.fromEntries(Astro.request.headers))}</code></p>

类型:ResponseInit & { readonly headers: Headers }

¥Type: ResponseInit & { readonly headers: Headers }

response 是标准 ResponseInit 对象。它具有以下结构。

¥response is a standard ResponseInit object. It has the following structure.

  • status:响应的数字状态代码,例如 200

  • statusText:与状态代码关联的状态消息,例如 'OK'

  • headers:可用于设置响应的 HTTP 标头的 Headers 实例。

Astro.response 用于设置页面响应的 statusstatusTextheaders

¥Astro.response is used to set the status, statusText, and headers for a page’s response.

---
if (condition) {
Astro.response.status = 404;
Astro.response.statusText = 'Not found';
}
---

或者设置标题:

¥Or to set a header:

---
Astro.response.headers.set('Set-Cookie', 'a=b; Path=/;');
---

类型:(path: string, status?: number) => Response

¥Type: (path: string, status?: number) => Response

Added in: astro@1.5.0

redirect() 返回一个 响应 对象,允许你重定向到另一个页面,并可选择提供 HTTP 响应状态代码 作为第二个参数。

¥redirect() returns a Response object that allows you to redirect to another page, and optionally provide an HTTP response status code as a second parameter.

页面(而不是子组件)必须 returnAstro.redirect() 的结果才能发生重定向。

¥A page (and not a child component) must return the result of Astro.redirect() for the redirect to occur.

对于静态生成的路由,这将使用 <meta http-equiv="refresh"> 标签 生成客户端重定向,并且不支持状态代码。

¥For statically-generated routes, this will produce a client redirect using a <meta http-equiv="refresh"> tag and does not support status codes.

对于按需渲染的路由,重定向时支持设置自定义状态代码。如果未指定,重定向将使用 302 状态代码提供。

¥For on-demand rendered routes, setting a custom status code is supported when redirecting. If not specified, redirects will be served with a 302 status code.

以下示例将用户重定向到登录页面:

¥The following example redirects a user to a login page:

src/pages/account.astro
---
import { isLoggedIn } from '../utils';
const cookie = Astro.request.headers.get('cookie');
// If the user is not logged in, redirect them to the login page
if (!isLoggedIn(cookie)) {
return Astro.redirect('/login');
}
---
<p>User information</p>

类型:(rewritePayload: string | URL | Request) => Promise<Response>

¥Type: (rewritePayload: string | URL | Request) => Promise<Response>

Added in: astro@4.13.0

rewrite() 允许你从不同的 URL 或路径提供内容,而无需将浏览器重定向到新页面。

¥rewrite() allows you to serve content from a different URL or path without redirecting the browser to a new page.

该方法接受字符串、URLRequest 作为路径的位置。

¥The method accepts either a string, a URL, or a Request for the location of the path.

使用字符串提供显式路径:

¥Use a string to provide an explicit path:

src/pages/index.astro
---
return Astro.rewrite("/login")
---

当你需要构建重写的 URL 路径时,请使用 URL 类型。以下示例通过从相对 "../" 路径创建新的 URL 来渲染页面的父路径:

¥Use a URL type when you need to construct the URL path for the rewrite. The following example renders a page’s parent path by creating a new URL from the relative "../" path:

src/pages/blog/index.astro
---
return Astro.rewrite(new URL("../", Astro.url))
---

使用 Request 类型完全控制发送到服务器的新路径的 Request。以下示例发送请求以渲染父页面,同时提供标头:

¥Use a Request type for complete control of the Request sent to the server for the new path. The following example sends a request to render the parent page while also providing headers:

src/pages/blog/index.astro
---
return Astro.rewrite(new Request(new URL("../", Astro.url), {
headers: {
"x-custom-header": JSON.stringify(Astro.locals.someValue)
}
}))
---

Added in: astro@2.4.0

locals 是一个用于在请求生命周期中存储和访问任意信息的对象。Astro.locals 是一个对象,包含中间件设置的 context.locals 对象中的任何值。使用它来访问 .astro 文件中中间件返回的数据。

¥locals is an object used to store and access arbitrary information during the lifecycle of a request. Astro.locals is an object containing any values from the context.locals object set by middleware. Use this to access data returned by middleware in your .astro files.

中间件函数可以读取和写入 context.locals 的值:

¥Middleware functions can both read and write the values of context.locals:

src/middleware.ts
import type { MiddlewareHandler } from 'astro';
export const onRequest: MiddlewareHandler = ({ locals }, next) => {
if (!locals.title) {
locals.title = "Default Title";
}
return next();
}

Astro 组件和 API 端点可以在渲染时从 locals 读取值:

¥Astro components and API endpoints can read values from locals when they render:

src/pages/Orders.astro
---
const title = Astro.locals.title;
---
<h1>{title}</h1>

类型:string | undefined

¥Type: string | undefined

Added in: astro@3.5.0

preferredLocale 是一个计算值,用于查找访问者的浏览器语言首选项与站点支持的语言环境之间的最佳匹配。

¥preferredLocale is a computed value to find the best match between your visitor’s browser language preferences and the locales supported by your site.

它是通过检查 i18n.locales 数组中配置的语言环境以及通过标头 Accept-Language 的用户浏览器支持的语言环境来计算的。如果不存在此类匹配,则该值为 undefined

¥It is computed by checking the configured locales in your i18n.locales array and the locales supported by the user’s browser via the header Accept-Language. This value is undefined if no such match exists.

此属性仅适用于按需渲染的路由,不能在预渲染的静态页面上使用。

¥This property is only available for routes rendered on demand and cannot be used on prerendered, static pages.

类型:string[] | undefined

¥Type: string[] | undefined

Added in: astro@3.5.0

preferredLocaleList 代表浏览器请求且你的网站支持的所有区域设置的数组。这会生成你的网站和访问者之间所有兼容语言的列表。

¥preferredLocaleList represents the array of all locales that are both requested by the browser and supported by your website. This produces a list of all compatible languages between your site and your visitor.

如果在语言环境数组中未找到浏览器请求的任何语言,则值为 []。当你不支持访问者的任何首选语言环境时,就会发生这种情况。

¥If none of the browser’s requested languages are found in your locales array, then the value is []. This occurs when you do not support any of your visitor’s preferred locales.

如果浏览器没有指定任何首选语言,则该值将为 i18n.locales:你支持的所有区域设置都将被无偏好的访问者视为同等偏好。

¥If the browser does not specify any preferred languages, then this value will be i18n.locales: all of your supported locales will be considered equally preferred by a visitor with no preferences.

此属性仅适用于按需渲染的路由,不能在预渲染的静态页面上使用。

¥This property is only available for routes rendered on demand and cannot be used on prerendered, static pages.

类型:string | undefined

¥Type: string | undefined

Added in: astro@3.5.6

使用 locales 配置中指定的语法从当前 URL 计算出的区域设置。如果 URL 不包含 /[locale]/ 前缀,则该值将默认为 i18n.defaultLocale

¥The locale computed from the current URL, using the syntax specified in your locales configuration. If the URL does not contain a /[locale]/ prefix, then the value will default to i18n.defaultLocale.

类型:(action: TAction) => ActionReturnType<TAction> | undefined

¥Type: (action: TAction) => ActionReturnType<TAction> | undefined

Added in: astro@4.15.0

getActionResult() 是一个返回 操作 提交结果的函数。这接受一个操作函数作为参数(例如 actions.logout),并在收到提交时返回 dataerror 对象。否则,它将返回 undefined

¥getActionResult() is a function that returns the result of an Action submission. This accepts an action function as an argument (e.g. actions.logout) and returns a data or error object when a submission is received. Otherwise, it will return undefined.

src/pages/index.astro
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.logout);
---
<form action={actions.logout}>
<button type="submit">Log out</button>
</form>
{result?.error && <p>Failed to log out. Please try again.</p>}

Added in: astro@4.15.0

callAction() 是一个用于直接从 Astro 组件调用操作处理程序的函数。此函数接受 Action 函数作为第一个参数(例如 actions.logout),并接受该操作接收的任何输入作为第二个参数。它将操作的结果作为 promise 返回。

¥callAction() is a function used to call an Action handler directly from your Astro component. This function accepts an Action function as the first argument (e.g. actions.logout) and any input that action receives as the second argument. It returns the result of the action as a promise.

src/pages/index.astro
---
import { actions } from 'astro:actions';
const { data, error } = await Astro.callAction(actions.logout, { userId: '123' });
---

类型:string

¥Type: string

Added in: astro@5.0.0

负责生成当前页面或路由的路由模式。在基于文件的路由中,这类似于项目中用于创建路由的文件路径。当集成为你的项目创建路由时,context.routePatterninjectRoute.pattern 的值相同。

¥The route pattern responsible for generating the current page or route. In file-based routing, this resembles the file path in your project used to create the route. When integrations create routes for your project, context.routePattern is identical to the value for injectRoute.pattern.

该值将以斜杠开头,看起来类似于相对于你的 src/pages/ 文件夹的页面组件的路径,但没有文件扩展名。

¥The value will start with a leading slash and look similar to the path of a page component relative to your src/pages/ folder without a file extension.

例如,文件 src/pages/en/blog/[slug].astro 将为 routePattern 返回 /en/blog/[slug]。你网站上由该文件生成的每个页面(例如 /en/blog/post-1//en/blog/post-2/ 等)都共享相同的 routePattern 值。在 index.* 路由的情况下,路由模式将不包含单词 “索引。” 例如,src/pages/index.astro 将返回 /

¥For example, the file src/pages/en/blog/[slug].astro will return /en/blog/[slug] for routePattern. Every page on your site generated by that file (e.g. /en/blog/post-1/, /en/blog/post-2/, etc.) shares the same value for routePattern. In the case of index.* routes, the route pattern will not include the word “index.” For example, src/pages/index.astro will return /.

你可以使用此属性了解哪个路由正在渲染你的组件。这允许你一起定位或分析类似生成的页面 URL。例如,你可以使用它有条件地渲染某些信息,或收集有关哪些路由较慢的指标。

¥You can use this property to understand which route is rendering your component. This allows you to target or analyze similarly-generated page URLs together. For example, you can use it to conditionally render certain information, or collect metrics about which routes are slower.

类型:AstroCookies

¥Type: AstroCookies

Added in: astro@1.4.0

cookies 包含用于读取和操作 按需渲染的路由 的 cookie 的实用程序。

¥cookies contains utilities for reading and manipulating cookies for routes rendered on demand.

¥Cookie utilities

类型:(key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined

¥Type: (key: string, options?: AstroCookieGetOptions) => AstroCookie | undefined

获取 cookie 作为 AstroCookie 对象,其中包含 value 和用于将 cookie 转换为非字符串类型的实用函数。

¥Gets the cookie as an AstroCookie object, which contains the value and utility functions for converting the cookie to non-string types.

类型:(key: string, options?: AstroCookieGetOptions) => boolean

¥Type: (key: string, options?: AstroCookieGetOptions) => boolean

该 cookie 是否存在。如果已通过 Astro.cookies.set() 设置 cookie,则将返回 true,否则,它将检查 Astro.request 中的 cookie。

¥Whether this cookie exists. If the cookie has been set via Astro.cookies.set() this will return true, otherwise, it will check cookies in the Astro.request.

类型:(key: string, value: string | object, options?: AstroCookieSetOptions) => void

¥Type: (key: string, value: string | object, options?: AstroCookieSetOptions) => void

将 cookie key 设置为给定值。这将尝试将 cookie 值转换为字符串。选项提供了设置 cookie 功能 的方法,例如 maxAgehttpOnly

¥Sets the cookie key to the given value. This will attempt to convert the cookie value to a string. Options provide ways to set cookie features, such as the maxAge or httpOnly.

类型:(key: string, options?: AstroCookieDeleteOptions) => void

¥Type: (key: string, options?: AstroCookieDeleteOptions) => void

通过将到期日期设置为过去(Unix 时间为 0)来使 cookie 无效。

¥Invalidates a cookie by setting the expiration date in the past (0 in Unix time).

一旦 cookie 为 “deleted”(已过期),Astro.cookies.has() 将返回 false,而 Astro.cookies.get() 将返回 AstroCookievalueundefined。删除 cookie 时可用的选项是:domainpathhttpOnlysameSitesecure

¥Once a cookie is “deleted” (expired), Astro.cookies.has() will return false and Astro.cookies.get() will return an AstroCookie with a value of undefined. Options available when deleting a cookie are: domain, path, httpOnly, sameSite, and secure.

类型:(cookies: AstroCookies) => void

¥Type: (cookies: AstroCookies) => void

将新的 AstroCookies 实例合并到当前实例中。任何新的 cookie 都将添加到当前实例,任何具有相同名称的 cookie 都将覆盖现有值。

¥Merges a new AstroCookies instance into the current instance. Any new cookies will be added to the current instance and any cookies with the same name will overwrite existing values.

类型:() => Iterator<string>

¥Type: () => Iterator<string>

获取将与响应一起发送的 Set-Cookie 标头值。

¥Gets the header values for Set-Cookie that will be sent out with the response.

¥AstroCookie Type

通过 Astro.cookies.get() 获取 cookie 返回的类型。它具有以下属性:

¥The type returned from getting a cookie via Astro.cookies.get(). It has the following properties:

类型:string

¥Type: string

cookie 的原始字符串值。

¥The raw string value of the cookie.

类型:() => Record<string, any>

¥Type: () => Record<string, any>

通过 JSON.parse() 解析 cookie 值,返回一个对象。如果 cookie 值不是有效的 JSON,则抛出此错误。

¥Parses the cookie value via JSON.parse(), returning an object. Throws if the cookie value is not valid JSON.

类型:() => number

¥Type: () => number

将 cookie 值解析为数字。如果不是有效数字,则返回 NaN。

¥Parses the cookie value as a Number. Returns NaN if not a valid number.

类型:() => boolean

¥Type: () => boolean

将 cookie 值转换为布尔值。

¥Converts the cookie value to a boolean.

Added in: astro@4.1.0

AstroCookieGetOption 接口允许你在获取 cookie 时指定选项。

¥The AstroCookieGetOption interface allows you to specify options when you get a cookie.

类型:(value: string) => string

¥Type: (value: string) => string

允许自定义如何将 cookie 反序列化为值。

¥Allows customization of how a cookie is deserialized into a value.

Added in: astro@4.1.0

AstroCookieSetOptions 是一个对象,可以在设置 cookie 时传递给 Astro.cookies.set(),以自定义 cookie 的序列化方式。

¥AstroCookieSetOptions is an object that can be passed to Astro.cookies.set() when setting a cookie to customize how the cookie is serialized.

类型:string

¥Type: string

指定域。如果未设置域,大多数客户端将解释为应用于当前域。

¥Specifies the domain. If no domain is set, most clients will interpret to apply to the current domain.

类型:Date

¥Type: Date

指定 cookie 过期的日期。

¥Specifies the date on which the cookie will expire.

类型:boolean

¥Type: boolean

如果为 true,则 cookie 将无法在客户端访问。

¥If true, the cookie will not be accessible client-side.

类型:number

¥Type: number

指定 cookie 有效的数字(以秒为单位)。

¥Specifies a number, in seconds, for which the cookie is valid.

类型:string

¥Type: string

指定应用 cookie 的域的子路径。

¥Specifies a subpath of the domain in which the cookie is applied.

类型:boolean | 'lax' | 'none' | 'strict'

¥Type: boolean | 'lax' | 'none' | 'strict'

指定 SameSite cookie 标头的值。

¥Specifies the value of the SameSite cookie header.

类型:boolean

¥Type: boolean

如果为 true,则 cookie 仅在 https 站点上设置。

¥If true, the cookie is only set on https sites.

类型:(value: string) => string

¥Type: (value: string) => string

允许自定义如何序列化 cookie。

¥Allows customizing how the cookie is serialized.

¥Deprecated object properties

Astro.glob() 是一种将许多本地文件加载到静态站点设置中的方法。

¥Astro.glob() is a way to load many local files into your static site setup.

src/components/my-component.astro
---
const posts = await Astro.glob('../pages/post/*.md'); // returns an array of posts that live at ./src/pages/post/*.md
---
<div>
{posts.slice(0, 3).map((post) => (
<article>
<h2>{post.frontmatter.title}</h2>
<p>{post.frontmatter.description}</p>
<a href={post.url}>Read more</a>
</article>
))}
</div>

.glob() 仅采用一个参数:你要导入的本地文件的相对 URL 全局。它是异步的,并返回匹配文件的导出数组。

¥.glob() only takes one parameter: a relative URL glob of which local files you’d like to import. It’s asynchronous and returns an array of the exports from matching files.

.glob() 不能接受变量或插入它们的字符串,因为它们不可静态分析。(请参阅 the imports guide 了解解决方法。)这是因为 Astro.glob() 是 Vite 的 import.meta.glob() 的封装器。

¥.glob() can’t take variables or strings that interpolate them, as they aren’t statically analyzable. (See the imports guide for a workaround.) This is because Astro.glob() is a wrapper of Vite’s import.meta.glob().

¥Markdown Files

使用 Astro.glob() 加载的 Markdown 文件返回以下 MarkdownInstance 接口:

¥Markdown files loaded with Astro.glob() return the following MarkdownInstance interface:

export interface MarkdownInstance<T extends Record<string, any>> {
/* Any data specified in this file's YAML frontmatter */
frontmatter: T;
/* The absolute file path of this file */
file: string;
/* The rendered path of this file */
url: string | undefined;
/* Astro Component that renders the contents of this file */
Content: AstroComponentFactory;
/** (Markdown only) Raw Markdown file content, excluding layout HTML and YAML frontmatter */
rawContent(): string;
/** (Markdown only) Markdown file compiled to HTML, excluding layout HTML */
compiledContent(): string;
/* Function that returns an array of the h1...h6 elements in this file */
getHeadings(): Promise<{ depth: number; slug: string; text: string }[]>;
default: AstroComponentFactory;
}

你可以选择使用 TypeScript 泛型为 frontmatter 变量提供类型。

¥You can optionally provide a type for the frontmatter variable using a TypeScript generic.

---
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 Files

Astro 文件具有以下接口:

¥Astro files have the following interface:

export interface AstroInstance {
/* The file path of this file */
file: string;
/* The URL for this file (if it is in the pages directory) */
url: string | undefined;
default: AstroComponentFactory;
}

¥Other Files

其他文件可能有各种不同的接口,但如果你确切知道无法识别的文件类型包含什么内容,Astro.glob() 就会接受 TypeScript 泛型。

¥Other files may have various different interfaces, but Astro.glob() accepts a TypeScript generic if you know exactly what an unrecognized file type contains.

---
interface CustomDataFile {
default: Record<string, any>;
}
const data = await Astro.glob<CustomDataFile>('../data/**/*.js');
---
Astro 中文网 - 粤ICP备13048890号