From 44e1d3e962d8d81c795fcecc74f4434040288a44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E7=91=9E=E4=B8=B0?= Date: Wed, 30 Aug 2023 18:17:55 +0800 Subject: [PATCH] i18n(zh-cn): Upgrade to Astro v3 guide for simplified Chinese (#4353) * i18n(zh-cn): uppercase http methods & some update. * Update why-astro.mdx * Update content-collection.mdx * Update cloudflare.mdx * Update markdown-content.mdx * Update styling.mdx * Update preact.mdx * Update react.mdx & solid-js.mdx * Update cli-reference.mdx * Update adapter & configuration reference * Update directives reference * Update integrations reference * Translate missing-sharp.mdx * Remove blank line * Update endpoints * Update endpoints * Update view transitions for v3 * upgrade to v3 translated * Update src/content/docs/zh-cn/guides/styling.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/concepts/why-astro.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/preact.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/preact.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/preact.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/upgrade-to/v3.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/upgrade-to/v3.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/react.mdx * Update src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx * Update src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx * Update src/content/docs/zh-cn/guides/integrations-guide/react.mdx * Update from v3-guide * Update src/content/docs/zh-cn/guides/integrations-guide/react.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/directives-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/preact.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/react.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/upgrade-to/v3.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/configuration-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/configuration-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/integrations-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/integrations-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/reference/integrations-reference.mdx Co-authored-by: Genteure * Update src/content/docs/zh-cn/guides/upgrade-to/v3.mdx Co-authored-by: Genteure * Update endpoints.mdx * Update endpoints.mdx * Update v3.mdx * Update v3.mdx * Update src/content/docs/zh-cn/guides/view-transitions.mdx Co-authored-by: Xiaoyue Lin <36526527+100gle@users.noreply.github.com> * Update src/content/docs/zh-cn/guides/upgrade-to/v3.mdx Co-authored-by: Genteure * Apply suggestions from code review Co-authored-by: Genteure * Update some from upstream * Update src/content/docs/zh-cn/reference/adapter-reference.mdx Co-authored-by: Xiaoyue Lin <36526527+100gle@users.noreply.github.com> --------- Co-authored-by: Genteure Co-authored-by: Xiaoyue Lin <36526527+100gle@users.noreply.github.com> Co-authored-by: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> --- src/content/docs/zh-cn/concepts/why-astro.mdx | 43 +- .../docs/zh-cn/core-concepts/endpoints.mdx | 119 ++-- .../zh-cn/core-concepts/project-structure.mdx | 5 - .../zh-cn/guides/backend/google-firebase.mdx | 25 +- .../docs/zh-cn/guides/content-collections.mdx | 12 +- .../docs/zh-cn/guides/deploy/netlify.mdx | 2 +- .../docs/zh-cn/guides/deploy/render.mdx | 2 +- .../docs/zh-cn/guides/deploy/vercel.mdx | 2 +- .../docs/zh-cn/guides/integrations-guide.mdx | 10 +- .../guides/integrations-guide/cloudflare.mdx | 30 +- .../guides/integrations-guide/markdoc.mdx | 26 + .../guides/integrations-guide/netlify.mdx | 35 +- .../zh-cn/guides/integrations-guide/node.mdx | 2 +- .../guides/integrations-guide/preact.mdx | 35 + .../zh-cn/guides/integrations-guide/react.mdx | 33 + .../guides/integrations-guide/solid-js.mdx | 35 + .../guides/integrations-guide/vercel.mdx | 34 +- .../docs/zh-cn/guides/markdown-content.mdx | 57 +- src/content/docs/zh-cn/guides/middleware.mdx | 4 +- src/content/docs/zh-cn/guides/rss.mdx | 10 +- .../zh-cn/guides/server-side-rendering.mdx | 4 +- src/content/docs/zh-cn/guides/styling.mdx | 31 +- .../docs/zh-cn/guides/troubleshooting.mdx | 4 +- .../docs/zh-cn/guides/upgrade-to/v3.mdx | 630 ++++++++++++++++++ .../docs/zh-cn/guides/view-transitions.mdx | 232 +++++-- src/content/docs/zh-cn/install/auto.mdx | 2 +- src/content/docs/zh-cn/install/manual.mdx | 2 +- .../docs/zh-cn/recipes/build-forms-api.mdx | 2 +- .../docs/zh-cn/recipes/call-endpoints.mdx | 8 +- src/content/docs/zh-cn/recipes/captcha.mdx | 4 +- .../zh-cn/reference/adapter-reference.mdx | 247 ++++++- .../docs/zh-cn/reference/api-reference.mdx | 24 +- .../docs/zh-cn/reference/cli-reference.mdx | 145 +++- .../reference/configuration-reference.mdx | 106 +-- .../zh-cn/reference/directives-reference.mdx | 9 +- .../docs/zh-cn/reference/error-reference.mdx | 1 + .../reference/errors/locals-not-an-object.mdx | 2 +- .../middleware-no-data-or-next-called.mdx | 2 +- .../errors/middleware-not-aresponse.mdx | 2 +- .../zh-cn/reference/errors/missing-sharp.mdx | 26 + .../errors/static-redirect-not-available.mdx | 2 +- .../errors/unsupported-image-format.mdx | 4 +- .../reference/image-service-reference.mdx | 2 +- .../reference/integrations-reference.mdx | 84 ++- src/content/docs/zh-cn/tutorial/1-setup/1.mdx | 8 +- .../docs/zh-cn/tutorial/5-astro-api/4.mdx | 2 +- src/i18n/zh-cn/nav.ts | 2 +- 47 files changed, 1653 insertions(+), 455 deletions(-) create mode 100644 src/content/docs/zh-cn/guides/upgrade-to/v3.mdx create mode 100644 src/content/docs/zh-cn/reference/errors/missing-sharp.mdx diff --git a/src/content/docs/zh-cn/concepts/why-astro.mdx b/src/content/docs/zh-cn/concepts/why-astro.mdx index c89ac94a126eb..a8ead377df02c 100644 --- a/src/content/docs/zh-cn/concepts/why-astro.mdx +++ b/src/content/docs/zh-cn/concepts/why-astro.mdx @@ -1,18 +1,18 @@ --- title: 为什么是 Astro? -description: Astro 是集多功能于一体的Web框架,用于构建快速、以内容为中心的网站。了解更多。 +description: Astro 是集多功能于一体的 Web 框架,用于构建快速、以内容为中心的网站。了解更多。 i18nReady: true --- -Astro 是**集多功能于一体的Web框架**,用于构建**快速、以内容为中心的网站**。 +Astro 是**集多功能于一体的 Web 框架**,用于构建**快速、以内容为中心的网站**。 -为什么选择 Astro 而不是其他的Web框架?以下的五个核心设计原则有助于解释我们为什么要构建 Astro,它需要解决的问题以及为什么 Astro 可能是您的项目或团队的最佳选择。 +为什么选择 Astro 而不是其他的 Web 框架?以下的五个核心设计原则有助于解释我们为什么要构建 Astro,它需要解决的问题以及为什么 Astro 可能是你的项目或团队的最佳选择。 -#### Astro是... +#### Astro 是... 1. [ **以内容为中心** ](#以内容为中心):Astro 专为内容丰富的网站而设计。 2. [ **服务器优先** ](#服务器优先):网站在服务器上渲染 HTML 时运行速度更快。 3. [ **默认快速** ](#默认快速):在 Astro 中构建缓慢的网站是不可能的。 -4. [ **易于使用** ](#易于使用):您不需要成为专家即可使用 Astro 构建某些内容。 +4. [ **易于使用** ](#易于使用):你不需要成为专家即可使用 Astro 构建某些内容。 5. [ **功能齐全且灵活** ](#功能齐全且灵活):超100多种 Astro 集成可供选择。 ## 以内容为中心 @@ -23,26 +23,20 @@ Astro 是**集多功能于一体的Web框架**,用于构建**快速、以内 这是了解 Astro 最重要的区别之一。 Astro 对内容的独特关注让 Astro 能够做出权衡并提供无与伦比的性能特性,而这些特性对于更多以应用程序为中心的 Web 框架来说是没有意义的。 :::tip -如果您的项目属于第二个“应用”阵营,Astro可能不是您项目的正确选择... **没关系!** 查看[Next.js](https://nextjs.org/)以获得比 Astro 更专注于应用程序的替代方案。 +如果你的项目属于第二个“应用”阵营,Astro 可能不是你项目的正确选择... **没关系!** 查看 [Next.js](https://nextjs.org/) 以获得比 Astro 更专注于应用程序的替代方案。 ::: - - - ## 服务器优先 -**Astro 尽可能利用服务器渲染而不是客户端渲染。** 这与传统服务器端框架(PHP、WordPress、Laravel、Ruby on Rails等)使用的方法相同,您不需要学习第二种服务端语言。 Astro 仍然使用 HTML、CSS和JavaScript(或TypeScript)。 +**Astro 尽可能利用服务器渲染而不是客户端渲染。** 这与传统服务器端框架(PHP、WordPress、Laravel、Ruby on Rails等)使用的方法相同,你不需要学习第二种服务端语言。 Astro 仍然使用 HTML、CSS和JavaScript(或TypeScript)。 -这种方法与其他现代 JavaScript Web框架 形成鲜明对比,如 Next.JS、SvelteKit、Nuxt、Remix 等。这些框架需要整个网站的客户端和服务器端渲染,以解决性能问题,这种方法被称为**单页应用程序(SPA),** 与 Astro 的**多页应用程序(MPA)** 方式形成鲜明对比。 +这种方法与其他现代 JavaScript Web 框架 形成鲜明对比,如 Next.JS、SvelteKit、Nuxt、Remix 等。这些框架需要整个网站的客户端和服务器端渲染,以解决性能问题,这种方法被称为**单页应用程序(SPA),** 与 Astro 的**多页应用程序(MPA)** 方式形成鲜明对比。 SPA模式有它的优势。然而,这些都是以牺牲额外的复杂性和性能权衡为代价,这些权衡会损坏页面性能——包括[可交互时间(TTI)](https://web.dev/interactive/) 等关键指标——这对于以内容为中心的网站没有多大意义,因为这些网站的首次加载性能至关重要。 📚 [进一步了解 **Astro MPA** 架构的独特之处](/zh-cn/concepts/mpa-vs-spa/) - - - ## 默认快速 -良好的性能很重要,对于以内容为中心的网站尤其至关重要。事实证明,糟糕的表现会让您失去参与度、转化率和金钱。列如: +良好的性能很重要,对于以内容为中心的网站尤其至关重要。事实证明,糟糕的表现会让你失去参与度、转化率和金钱。列如: - 每快 100ms → 转化率增加 1% ([Mobify](https://web.dev/why-speed-matters/), 收入 +$380,000/年) - 每快 50% → 销售额增加 12% ([AutoAnything](https://www.digitalcommerce360.com/2010/08/19/web-accelerator-revs-conversion-and-sales-autoanything/)) - 每快 20% → 转换率增加 10% ([Furniture Village](https://www.thinkwithgoogle.com/intl/en-gb/marketing-strategies/app-and-mobile/furniture-village-and-greenlight-slash-page-load-times-boosting-user-experience/)) @@ -56,26 +50,21 @@ Astro 的魔力在于它如何将上述两个值(内容焦点于服务器优 与使用最受欢迎的 React Web框架 构建相同的网站进行比较,Astro 网站的[加载速度快40%,JavaScript减少90%](https://twitter.com/t3dotgg/status/1437195415439360003) 。请对我们的结论半信半疑:观看 Astro 的现场直播 让 Ryan Carniato(Solid.js和Marko的创造者) [无言以对](https://youtu.be/2ZEMb_H-LYE?t=8163)。 - - ## 易于使用 -**Astro的目标是让每位Web开发人员都可以访问。** Astro 被设计成熟悉和平易近人的感觉,无论技能水平或过去的Web开发经验如何。 +**Astro 的目标是让每位 Web 开发者都易于理解。** Astro 被设计成熟悉和平易近人的感觉,无论技能水平或过去的 Web 开发经验如何。 -我们首先确保您可以使用您已经了解的任何喜欢的 UI 组件语言。在 Astro 项目中创建新的 UI 组件时使用 React、Preact、Svelte、Vue、Solid、Lit 和其他一些组件都是被支持的。 +我们首先确保你可以使用你已经了解的任何喜欢的 UI 组件语言。在 Astro 项目中创建新的 UI 组件时使用 React、Preact、Svelte、Vue、Solid、Lit 和其他一些组件都是被支持的。 我们为了 Astro 也能有一个很好的内置组件语言,我们创建了自己 `.astro` UI语言。它很大程度上深受 HTML 的影响:任何有效的 HTML 部分都已经是有效的 Astro 组件,它还结合了我们从其他组件中借用的一些功能,如:React 的 JSX 表达式和(像 Svelte 和 Vue 一样的)默认 CSS 作用域。这种与 HTML 的相似性也使得使用渐进式增强和通用可访问性模式变得更加容易,而无需任何开销。 -Astro 的设计比其他UI框架和语言更简单,其中一个重要原因是 Astro 被设计为在服务器上渲染而不是浏览器,这意味着您无需担心:React Hooks、stale closures(React)、refs(Vue)、observables(Svelte)、atoms、selectors、reactions or derivations。服务器上没有响应式,因此这些复杂性都消失了。 - -我们最喜欢的谚语之一是:**选择加入复杂性。** 我们设计 Astro 是为了尽可能多地从开发人员体验中消除“所需的复杂性”,尤其是您首次加入时。您可以在 Astro中使用 HTML和CSS构建“Hello World”示例网站。然后当您需要构建更强大的功能时,您可以随时获得新功能和API。 - - +Astro 的设计比其他UI框架和语言更简单,其中一个重要原因是 Astro 被设计为在服务器上渲染而不是浏览器,这意味着你无需担心:hooks (React)、stale closures (还是 React)、refs (Vue)、observables (Svelte)、atoms、selectors、reactions、或 derivations。服务器上没有响应式,因此这些复杂性都消失了。 +我们最喜欢的说法之一是:**复杂性是可选的。** 我们设计 Astro 是为了尽可能多地从开发人员体验中消除“必须的复杂性”,尤其是你首次加入时。你可以在 Astro 中使用 HTML 和 CSS 构建 “Hello World” 示例网站。然后当你需要构建更强大的功能时,你可以随时获得新功能和 API。 ## 功能齐全且灵活 -**Astro 是集多功能于一体的 Web 框架,提供了构建网站所需的一切** Astro 包括组件语法、基于文件的路由、静态资源处理、构建处理、捆绑、优化、数据获取等。您可以在不超过 Astro 核心功能集 的情况下构建出色的网站。 +**Astro 是集多功能于一体的 Web 框架,提供了构建网站所需的一切** Astro 包括组件语法、基于文件的路由、静态资源处理、构建处理、捆绑、优化、数据获取等。你只使用 Astro 核心功能集就可构建出色的网站。 -如果您需要更多的控制,你可以通过 [React](https://www.npmjs.com/package/@astrojs/react), [Svelte](https://www.npmjs.com/package/@astrojs/svelte), [Vue](https://www.npmjs.com/package/@astrojs/vue), [Tailwind CSS](https://www.npmjs.com/package/@astrojs/tailwind), [MDX](https://www.npmjs.com/package/@astrojs/mdx), [image optimizations](https://www.npmjs.com/package/@astrojs/image)等[100多个集成](https://astro.build/integrations/)。 扩展 Astro 只需要一个命令 [即可连接您喜欢的CMS](/zh-cn/guides/cms/) 或 [部署到您喜欢的服务器](/zh-cn/guides/deploy/) +如果你需要更多的控制,你可以通过 [React](https://www.npmjs.com/package/@astrojs/react), [Svelte](https://www.npmjs.com/package/@astrojs/svelte), [Vue](https://www.npmjs.com/package/@astrojs/vue), [Tailwind CSS](https://www.npmjs.com/package/@astrojs/tailwind), [MDX](https://www.npmjs.com/package/@astrojs/mdx) 等[100多个集成](https://astro.build/integrations/)。 扩展 Astro 只需要一个命令 [即可连接你喜欢的 CMS](/zh-cn/guides/cms/) 或 [部署到你喜欢的托管平台](/zh-cn/guides/deploy/) -Astro 与 UI 无关,这意味着您可以自带 UI 框架(BYOF)。React、Preact、Solid 、Svelte、Vue 和 Lit 都在 Astro 中得到官方支持。您甚至可以在同一页面上混合和匹配不同的框架,使未来的迁移更容易,并防止项目锁定到单个框架。 +Astro 与 UI 无关,这意味着你可以自带 UI 框架(BYOF)。React、Preact、Solid 、Svelte、Vue 和 Lit 都在 Astro 中得到官方支持。你甚至可以在同一页面上混合和匹配不同的框架,使未来的迁移更容易,并防止项目锁定到单个框架。 diff --git a/src/content/docs/zh-cn/core-concepts/endpoints.mdx b/src/content/docs/zh-cn/core-concepts/endpoints.mdx index 770eb41438a5f..214b74e7ed816 100644 --- a/src/content/docs/zh-cn/core-concepts/endpoints.mdx +++ b/src/content/docs/zh-cn/core-concepts/endpoints.mdx @@ -13,30 +13,26 @@ Astro 允许你创建自定义端点来提供任何类型的数据。你可以 要想要创建自定义端点,请将 `.js` 或 `.ts` 文件添加到 `/pages` 目录。`.js` 或 `.ts` 这样的扩展名将在构建过程中被删除,因此文件名中应包含你要创建的数据的扩展名。例如,文件 `src/pages/data.json.ts` 将被构建为 API 端点 `/data.json`。 -端点导出一个 `get` 函数(可选的以 `async` 导出),该函数接收具有类似于 Astro 全局属性的上下文对象。它返回一个带有 `body` 的对象,Astro 将在构建时调用它并使用 `body` 中的内容来生成文件。 +端点导出一个 `GET` 函数(可选的以 `async` 导出),该函数接收具有类似于 `Astro` 全局属性的 [上下文对象](/zh-cn/reference/api-reference/#端点上下文)。在这里,它返回一个带有 `name` 和 `url` 的 Response 对象,Astro 将在构建时调用它并使用 `body` 中的内容来生成文件。 ```js // 输出: /builtwith.json -export async function get({params, request}) { - return { - body: JSON.stringify({ +export async function GET({params, request}) { + return new Response( + JSON.stringify({ name: 'Astro', - url: 'https://astro.build/', - }), - }; + url: 'https://astro.build/' + }) + ) } ``` -返回对象还可以具有 `encoding` 属性。它可以是任何可以被 Node.js 的 `fs.writeFile` 方法接收的 [`BufferEncoding`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/bdd02508ddb5eebcf701fdb8ffd6e84eabf47885/types/node/buffer.d.ts#L169)。例如,生成一个二进制png图像: +从 Astro v3.0 开始,返回的 `Response` 对象不再需要包含 `encoding` 属性。例如,生成一个二进制 png 图像: -```ts title="src/pages/astro-logo.png.ts" {6} -export async function get({ params, request }) { +```ts title="src/pages/astro-logo.png.ts" {3} +export async function GET({ params, request }) { const response = await fetch("https://docs.astro.build/assets/full-logo-light.png"); - const buffer = Buffer.from(await response.arrayBuffer()); - return { - body: buffer, - encoding: 'binary', - }; + return new Response(await response.arrayBuffer()); } ``` @@ -45,26 +41,25 @@ export async function get({ params, request }) { ```js import type { APIRoute } from 'astro'; -export const get: APIRoute = async ({ params, request }) => { -... +export const GET: APIRoute = async ({ params, request }) => {...} ``` ### `params` 和动态路由 -端点支持与页面相同的[动态路由](/zh-cn/core-concepts/routing/#动态路由)功能。使用中括号包裹参数作为文件名,并导出 [`getStaticPaths()` 函数](/zh-cn/reference/api-reference/#getstaticpaths)。然后,你可以使用传递给 API 端点函数的 `params` 属性访问参数: +端点支持与页面相同的 [动态路由](/zh-cn/core-concepts/routing/#动态路由) 功能。使用中括号包裹参数作为文件名,并导出 [`getStaticPaths()` 函数](/zh-cn/reference/api-reference/#getstaticpaths)。然后,你可以使用传递给 API 端点函数的 `params` 属性访问参数: ```ts title="src/pages/api/[id].json.ts" import type { APIRoute } from 'astro'; const usernames = ["张三", "李四", "王五"] -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { const id = params.id; - return { - body: JSON.stringify({ + return new Response( + JSON.stringify({ name: usernames[id] }) - } + ) }; export function getStaticPaths () { @@ -85,25 +80,25 @@ export function getStaticPaths () { ```ts title="src/pages/request-path.json.ts" import type { APIRoute } from 'astro'; -export const get: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ +export const GET: APIRoute = ({ params, request }) => { + return new Response( + JSON.stringify({ path: new URL(request.url).pathname }) - }; + ) } ``` ## 服务器端点(API 路由) -[静态文件的端点](#静态文件端点)部分中描述的所有内容均可以在 SSR 模式下使用:文件可以导出一个名为 `get` 的函数,该函数接收具有类似于 `Astro` 全局属性的上下文对象 +[静态文件的端点](#静态文件端点) 部分中描述的所有内容均可以在 SSR 模式下使用:文件可以导出一个名为 `get` 的函数,该函数接收具有类似于 `Astro` 全局属性的 [上下文对象](/zh-cn/reference/api-reference/#端点上下文)。 但是,不同于静态模式,当你使用 `server` 模式时,端点将在请求时被构建。这解锁了在构建时不可用的新特性,并允许你构建 API 路由以监听请求,并在服务器上安全地执行代码。 :::note -在尝试这些示例之前,请务必确认已经[启用了 SSR](/zh-cn/guides/server-side-rendering/#启用-ssr)。 +在尝试这些示例之前,请务必确认已经 [启用了 SSR](/zh-cn/guides/server-side-rendering/#启用-ssr)。 ::: 服务器端点可以在不导出 `getStaticPaths` 的情况下访问 `params`。服务器端点可以返回一个 [`Response`](https://developer.mozilla.org/zh-CN/docs/Web/API/Response) 对象,其允许你为返回的数据设置 `status codes` 和 `headers` @@ -111,7 +106,7 @@ export const get: APIRoute = ({ params, request }) => { ```js title="src/pages/[id].json.js" import { getProduct } from '../db'; -export async function get({ params }) { +export async function GET({ params }) { const id = params.id; const product = await getProduct(id); @@ -122,12 +117,14 @@ export async function get({ params }) { }); } - return new Response(JSON.stringify(product), { - status: 200, - headers: { - "Content-Type": "application/json" + return new Response( + JSON.stringify(product), { + status: 200, + headers: { + "Content-Type": "application/json" + } } - }); + ); } ``` @@ -136,7 +133,7 @@ export async function get({ params }) { 在 SSR 模式下,需要提供 `Content-Type` 头来返回图像。在这种情况下,使用 `Response` 对象来指定 `headers` 属性。例如,生成一个二进制 `.png` 图像: ```ts title="src/pages/astro-logo.png.ts" -export async function get({ params, request }) { +export async function GET({ params, request }) { const response = await fetch("https://docs.astro.build/assets/full-logo-light.png"); const buffer = Buffer.from(await response.arrayBuffer()); return new Response(buffer, { @@ -147,56 +144,48 @@ export async function get({ params, request }) { ### HTTP 方法 -除了 `get` 函数,您还可以使用任何 [HTTP 方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods) 作为名称导出函数。当有请求进来时,Astro 会检查该方法并调用相应的函数。 - -你还可以导出 `all` 函数以匹配任何没有相应导出函数的方法。如果请求没有匹配的方法,它将重定向到您网站的 [404 页面](/zh-cn/core-concepts/astro-pages/#自定义-404-错误页面)。 +除了 `GET` 函数,你还可以使用任何 [HTTP 方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods) 作为名称导出函数。当有请求进来时,Astro 会检查该方法并调用相应的函数。 - - -:::note -由于 `delete` 是 JavaScript 中的保留关键字,请导出名为 `del` 的函数以匹配 DELETE 方法。 -::: +你还可以导出 `ALL` 函数以匹配任何没有相应导出函数的方法。如果请求方法不匹配,它将重定向到你的网站的 [404 页面](/zh-cn/core-concepts/astro-pages/#自定义-404-错误页面)。 ```ts title="src/pages/methods.json.ts" -export const get: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ +export const GET: APIRoute = ({ params, request }) => { + return new Response(JSON.stringify({ message: "This was a GET!" }) - } -}; + ) +} -export const post: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: "这是一个 POST 请求!" +export const POST: APIRoute = ({ request }) => { + return new Response(JSON.stringify({ + message: "This was a POST!" }) - } + ) } -export const del: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: "这是一个 DELETE 请求!" +export const DELETE: APIRoute = ({ request }) => { + return new Response(JSON.stringify({ + message: "This was a DELETE!" }) - } + ) } -export const all: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: `这是一个 ${request.method} 请求!` +export const ALL: APIRoute = ({ request }) => { + return new Resonse(JSON.stringify({ + message: `This was a ${request.method}!` }) - } + ) } ``` + + ### `request` 在 SSR 模式下,`request` 属性返回一个可用的 [`Request`](https://developer.mozilla.org/zh-CN/docs/Web/API/Request) 对象,该对象引用当前请求。这允许你接收数据并检查 [`headers`](https://developer.mozilla.org/zh-CN/docs/Web/API/Request/headers): ```ts title="src/pages/test-post.json.ts" -export const post: APIRoute = async ({ request }) => { +export const POST: APIRoute = async ({ request }) => { if (request.headers.get("Content-Type") === "application/json") { const body = await request.json(); const name = body.name; @@ -217,7 +206,7 @@ export const post: APIRoute = async ({ request }) => { ```js title="src/pages/links/[id].js" {14} import { getLinkUrl } from '../db'; -export async function get({ params }) { +export async function GET({ params }) { const { id } = params; const link = await getLinkUrl(id); diff --git a/src/content/docs/zh-cn/core-concepts/project-structure.mdx b/src/content/docs/zh-cn/core-concepts/project-structure.mdx index 81c5b70e9b1d2..3a6edf3f73f67 100644 --- a/src/content/docs/zh-cn/core-concepts/project-structure.mdx +++ b/src/content/docs/zh-cn/core-concepts/project-structure.mdx @@ -65,11 +65,6 @@ Astro 处理、压缩和打包你的 `src/` 文件以创建最终传递到浏览 虽然本指南描述了 Astro 社区中使用的一些流行约定,但 Astro 保留的目录只有 `src/pages/` 和 `src/content/` 。你可以自由的以最适合自己的方式重命名和重新组织任何其他目录。 ::: - -### `src/assets` - -[`src/assets`](/zh-cn/guides/assets/) 目录推荐用于存储由 Astro 处理的资源(例如:图片)。这不是必需的,也不是特殊的保留文件夹。 - ### `src/components` **组件**是你在 HTML 页面中可重复使用的代码单元。它可以是 [Astro 组件](/zh-cn/core-concepts/astro-components/) 或是像 React 或 Vue 这样的[UI框架组件](/zh-cn/core-concepts/framework-components/)。通常将你项目中所有组件都分组放在这个文件夹中。 diff --git a/src/content/docs/zh-cn/guides/backend/google-firebase.mdx b/src/content/docs/zh-cn/guides/backend/google-firebase.mdx index 3c58a88a1db72..d9c09f86425f5 100644 --- a/src/content/docs/zh-cn/guides/backend/google-firebase.mdx +++ b/src/content/docs/zh-cn/guides/backend/google-firebase.mdx @@ -188,7 +188,7 @@ import type { APIRoute } from "astro"; import { app } from "../../../firebase/server"; import { getAuth } from "firebase-admin/auth"; -export const get: APIRoute = async ({ request, cookies, redirect }) => { +export const GET: APIRoute = async ({ request, cookies, redirect }) => { const auth = getAuth(app); /* 从请求头中获取 令牌 */ @@ -233,7 +233,7 @@ export const get: APIRoute = async ({ request, cookies, redirect }) => { ```ts title="src/pages/api/auth/signout.ts" import type { APIRoute } from "astro"; -export const get: APIRoute = async ({ redirect, cookies }) => { +export const GET: APIRoute = async ({ redirect, cookies }) => { cookies.delete("session", { path: "/", }); @@ -252,7 +252,7 @@ import type { APIRoute } from "astro"; import { getAuth } from "firebase-admin/auth"; import { app } from "../../../firebase/server"; -export const post: APIRoute = async ({ request, redirect }) => { +export const POST: APIRoute = async ({ request, redirect }) => { const auth = getAuth(app); /* 获取表单数据 */ @@ -352,8 +352,8 @@ import Layout from "../layouts/Layout.astro"; /* 校验用户是否已经通过身份验证 */ const auth = getAuth(app); -const sessionCookie = Astro.cookies.get("session").value; -if (sessionCookie) { +if (Astro.cookies.has("session")) { + const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); if (decodedCookie) { return Astro.redirect("/dashboard"); @@ -429,11 +429,10 @@ import Layout from "../layouts/Layout.astro"; const auth = getAuth(app); /* 检查当前会话 */ -const sessionCookie = Astro.cookies.get("session").value; - -if (!sessionCookie) { +if (!Astro.cookies.has("session")) { return Astro.redirect("/signin"); } +const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); const user = await auth.getUser(decodedCookie.uid); @@ -471,8 +470,8 @@ import Layout from "../layouts/Layout.astro"; /* 校验用户是否已经通过身份验证 */ const auth = getAuth(app); -const sessionCookie = Astro.cookies.get("session").value; -if (sessionCookie) { +if (Astro.cookies.has("session")) { + const sessionCookie = Astro.cookies.get("session").value; const decodedCookie = await auth.verifySessionCookie(sessionCookie); if (decodedCookie) { return Astro.redirect("/dashboard"); @@ -583,7 +582,7 @@ import type { APIRoute } from "astro"; import { app } from "../../../firebase/server"; import { getFirestore } from "firebase-admin/firestore"; -export const post: APIRoute = async ({ request, redirect }) => { +export const POST: APIRoute = async ({ request, redirect }) => { const formData = await request.formData(); const name = formData.get("name")?.toString(); const age = formData.get("age")?.toString(); @@ -625,7 +624,7 @@ import { getFirestore } from "firebase-admin/firestore"; const db = getFirestore(app); const friendsRef = db.collection("friends"); -export const post: APIRoute = async ({ params, redirect, request }) => { +export const POST: APIRoute = async ({ params, redirect, request }) => { const formData = await request.formData(); const name = formData.get("name")?.toString(); const age = formData.get("age")?.toString(); @@ -657,7 +656,7 @@ export const post: APIRoute = async ({ params, redirect, request }) => { return redirect("/dashboard"); }; -export const del: APIRoute = async ({ params, redirect }) => { +export const DELETE: APIRoute = async ({ params, redirect }) => { if (!params.id) { return new Response("Cannot find friend", { status: 404, diff --git a/src/content/docs/zh-cn/guides/content-collections.mdx b/src/content/docs/zh-cn/guides/content-collections.mdx index c4984056676cd..af6a7dc43e1f7 100644 --- a/src/content/docs/zh-cn/guides/content-collections.mdx +++ b/src/content/docs/zh-cn/guides/content-collections.mdx @@ -397,6 +397,16 @@ const draftBlogEntries = await getCollection('blog', ({ data }) => { }); ``` +你还可以创建草稿页面,这些页面在运行开发服务器时可用,但在生产中不会构建: + +```js +// 示例:仅当构建生产时,才过滤掉具有 `draft: true` 的内容条目 +import { getCollection } from 'astro:content'; +const blogEntries = await getCollection('blog', ({ data }) => { + return import.meta.env.PROD ? data.draft !== true : true; +}); +``` + filter 参数还支持按集合中的嵌套目录进行筛选。由于 `id` 包含完整的嵌套路径,因此可以根据每个 `id` 的开头进行筛选,只返回特定嵌套目录中的项目: ```js @@ -706,7 +716,7 @@ const { Content } = await entry.render(); import rss from "@astrojs/rss"; import { getCollection } from "astro:content"; - export async function get() { + export async function GET() { const posts = await getCollection('posts'); return rss({ title: 'Astro Learner | Blog', diff --git a/src/content/docs/zh-cn/guides/deploy/netlify.mdx b/src/content/docs/zh-cn/guides/deploy/netlify.mdx index e589f16d2510a..a7ce1cece84cb 100644 --- a/src/content/docs/zh-cn/guides/deploy/netlify.mdx +++ b/src/content/docs/zh-cn/guides/deploy/netlify.mdx @@ -121,7 +121,7 @@ npx astro add netlify ### 设置 Node.js 版本 -如果你在 Netlify 上使用的是旧版的 [构建镜像](https://docs.netlify.com/configure-builds/get-started/#build-image-selection)(Xenial),请确保你已经设置了 Node.js 的版本。Astro 需要 v16.12.0 或更高版本。 +如果你在 Netlify 上使用的是旧版的 [构建镜像](https://docs.netlify.com/configure-builds/get-started/#build-image-selection)(Xenial),请确保你已经设置了 Node.js 的版本。Astro 需要 v18.14.1 或更高版本。 你可以使用下面的方法在 [Netlify 中指定 Node.js 版本](https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript): - 在你的项目根目录中存放一个 [`.nvmrc`](https://github.com/nvm-sh/nvm#nvmrc) 文件 diff --git a/src/content/docs/zh-cn/guides/deploy/render.mdx b/src/content/docs/zh-cn/guides/deploy/render.mdx index dad35a75563fe..9afa362cf2f56 100644 --- a/src/content/docs/zh-cn/guides/deploy/render.mdx +++ b/src/content/docs/zh-cn/guides/deploy/render.mdx @@ -15,5 +15,5 @@ i18nReady: true 4. 为你的网站取一个名称,选择分支,并指定构建命令和发布目录: - **构建命令:** `npm run build` - **发布目录:** `dist` - - **环境变量(高级):** Render 默认使用 Node.js 14.17.0,但 Astro [需要更高版本](/zh-cn/install/auto/#前提准备)。添加一个名为 `NODE_VERSION` 的环境变量,值为 `16.12.0` 或更高版本,告诉 Render 使用兼容的 Node.js 版本。或者,向项目添加一个 [`.node-version`](https://render.com/docs/node-version) 或 [`.nvmrc`](https://render.com/docs/node-version) 文件来指定一个 Node.js 版本。 + - **环境变量(高级):** Render 默认使用 Node.js 14.17.0,但 Astro [需要更高版本](/zh-cn/install/auto/#前提准备)。添加一个名为 `NODE_VERSION` 的环境变量,值为 `18.14.1` 或更高版本,告诉 Render 使用兼容的 Node.js 版本。或者,向项目添加一个 [`.node-version`](https://render.com/docs/node-version) 或 [`.nvmrc`](https://render.com/docs/node-version) 文件来指定一个 Node.js 版本。 5. 点击 **Create Static Site** 按钮。 diff --git a/src/content/docs/zh-cn/guides/deploy/vercel.mdx b/src/content/docs/zh-cn/guides/deploy/vercel.mdx index 6681829283c31..6a3eba4621c3d 100644 --- a/src/content/docs/zh-cn/guides/deploy/vercel.mdx +++ b/src/content/docs/zh-cn/guides/deploy/vercel.mdx @@ -82,4 +82,4 @@ npx astro add vercel ### 升级到 Astro 2.0 -Astro v2.0 不再支持 Node 14,因此请确保你的项目使用 **Node `16.12.0` 或更高版本**。你可以在项目设置的 “通用” 页面中的 “构建步骤和无服务器函数” 下 [自定义所使用的 Node.js 版本](https://vercel.com/changelog/node-js-version-now-customizable-in-the-project-settings)。 +Astro v2.0 不再支持 Node 14,因此请确保你的项目使用 **Node `18.14.1` 或更高版本**。你可以在项目设置的 “通用” 页面中的 “构建步骤和无服务器函数” 下 [自定义所使用的 Node.js 版本](https://vercel.com/changelog/node-js-version-now-customizable-in-the-project-settings)。 diff --git a/src/content/docs/zh-cn/guides/integrations-guide.mdx b/src/content/docs/zh-cn/guides/integrations-guide.mdx index c5b3d2714b0c4..f2d27b96f5fb2 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide.mdx @@ -126,17 +126,17 @@ integrations: [ ```shell - npm uninstall @astrojs/image + npm uninstall @astrojs/react ``` ```shell - pnpm uninstall @astrojs/image + pnpm uninstall @astrojs/react ``` ```shell - yarn remove @astrojs/image + yarn remove @astrojs/react ``` @@ -146,11 +146,11 @@ integrations: [ ```js title="astro.config.mjs" del={3,7} import { defineConfig } from 'astro/config' -import image from "@astrojs/image"; +import react from "@astrojs/react"; export default defineConfig({ integrations: [ - image() + react() ] }) ``` diff --git a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx index 88bebd49d91f5..1c591aafa6083 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/cloudflare.mdx @@ -55,23 +55,37 @@ export default defineConfig({ 默认为 `"advanced"` -Cloudflare Pages 有两种不同的部署模式,`advanced` 模式会在 `dist` 目录中寻找 `_worker.js` 文件,而 `directory` 模式会在项目根目录中的 functions 文件夹中编译 worker。 +Cloudflare Pages 有两种不同的部署模式,`advanced` 模式会在 `dist` 目录中寻找 `_worker.js` 文件,而 `directory` 模式会在项目根目录中的 functions 文件夹中编译 worker。对于大多数项目来说,适配器的默认值 `"advanced"` 就足够了,`dist` 文件夹将会包含已编译的项目。 -对于大多数项目来说,适配器的默认值 `"advanced"` 就足够了,`dist` 文件夹将会包含已编译的项目。若切换到 `directory` 模式,那么你将可以使用 [Pages 插件](https://developers.cloudflare.com/pages/platform/functions/plugins/)(如 [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/))或编写自定义代码以启用日志记录。 +#### `mode:directory` -在 `directory` 模式下,默认情况下,适配器会以相同的方式编译应用程序的客户端部分,但也会将 worker 脚本移动到项目根目录中的 `functions` 文件夹中。在这种情况下,适配器只会在该文件夹中放置一个 `[[path]].js` 文件,这样你就可以添加其他插件和页面的中间件,并将其归入版本控制。 - -使用构建配置 `split: true`,适配器将为每个页面编译一个单独的包。启用这个选项需要手动维护 `functions` 文件夹。Astro 生成的文件会覆盖现有的具有相同名称的 `functions` 文件,因此你必须为每个手动添加的文件选择唯一的文件名。此外,适配器永远不会清空 `functions` 文件夹中过时的文件,所以当你删除页面时,必须手动清理该文件夹。 - -请注意,此适配器不支持使用 [Cloudflare Pages 中间件](https://developers.cloudflare.com/pages/platform/functions/middleware/)。Astro 将会将 [Astro 中间件](/zh-cn/guides/middleware/) 打包到每个页面中。 +切换到 `directory` 模式允许你使用 [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/),例如 [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) 或编写自定义代码来启用日志记录。 ```ts -// directory 模式 +// astro.config.mjs export default defineConfig({ adapter: cloudflare({ mode: 'directory' }), }); ``` +在 `directory` 模式下,适配器默认会以与 `advanced` 模式相同的方式编译应用程序的客户端部分,但是将 worker 脚本移动到项目根目录中的 `functions` 文件夹中。在这种情况下,适配器只会在该文件夹中放置一个 `[[path]].js`,允许你添加其他插件和页面中间件,这些插件和页面中间件可以检入版本控制。 + +要为每个页面编译一个单独的 bundle,请在 Cloudflare 适配器配置中设置 `functionPerPath` 选项。该选项需要手动维护 `functions` 文件夹。Astro 发出的文件将覆盖具有相同名称的现有 `functions` 文件,因此你必须为手动添加的每个文件选择唯一的文件名。此外,适配器永远不会清空 `functions` 文件夹中的过时文件,因此当你删除页面时,必须手动清理该文件夹。 + +```diff +import {defineConfig} from "astro/config"; +import cloudflare from '@astrojs/cloudflare'; + +export default defineConfig({ + adapter: cloudflare({ + mode: 'directory', ++ functionPerRoute: true + }) +}) +``` + +请注意,此适配器不支持使用 [Cloudflare 页面中间件](https://developers.cloudflare.com/pages/platform/functions/middleware/)。Astro 将会把 [Astro 中间件](/zh-cn/guides/middleware/) 打包到每个页面中。 + ## 启用预览 为了使预览功能正常工作,你需要安装 `wrangler` diff --git a/src/content/docs/zh-cn/guides/integrations-guide/markdoc.mdx b/src/content/docs/zh-cn/guides/integrations-guide/markdoc.mdx index bf961710f2a61..c0911430ff556 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/markdoc.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/markdoc.mdx @@ -342,6 +342,32 @@ export default defineMarkdocConfig({ 📚 [查看 Markdoc 文档](https://markdoc.dev/docs/functions#creating-a-custom-function) 了解更多关于在你的内容中使用变量或函数的信息。 +### Markdoc 语言服务器 + +如果你使用的是 VS Code,有一个官方的 [Markdoc 语言扩展](https://marketplace.visualstudio.com/items?itemName=Stripe.markdoc-language-support),它包括了为配置的标签提供语法高亮和自动完成。[在 GitHub 上查看语言服务器](https://github.com/markdoc/language-server.git) 的更多信息。 + +要设置这个扩展,创建一个 `markdoc.config.json` 文件到项目根目录,内容如下: +```json +[ + { + "id": "my-site", + "path": "src/content", + "schema": { + "path": "markdoc.config.mjs", + "type": "esm", + "property": "default", + "watch": true + } + } +] +``` +`schema` 属性 包含了为 Astro 内容集合配置语言服务器的所有信息。它接受以下属性: +* `path`: 配置文件的路径。 +* `type`: 配置文件使用的模块类型(`esm` 允许 `import` 语法)。 +* `property`: 包含配置对象的导出属性名称。 +* `watch`: 告诉服务器监听配置中的更改。 +顶级 `path` 属性告诉服务器内容位于哪里。由于 Markdoc 是特定于内容集合的,因此可以使用 `src/content`。 + ### 传递 Markdoc 变量 你可能需要将 [变量][markdoc-variables] 传递给你的内容。当传递 SSR 参数时,这是很有用的,比如 A/B 测试。 diff --git a/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx b/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx index 7a01d79a1f85a..1471c75f78a9f 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx @@ -56,28 +56,11 @@ pnpm astro add netlify }); ``` -### Edge Functions - -Netlify 有两个 serverless 平台,[Netlify Functions](https://docs.netlify.com/functions/overview/) 和 [Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/)。使用 Edge Functions,你的代码分布在更接近用户的地方,降低延迟。 - -为了使用 Edge Functions 部署,使用 Astro 配置文件中的 `netlify/edge-functions` 而不是 `netlify/functions`。 - -```js ins={3} -// astro.config.mjs -import { defineConfig } from 'astro/config'; -import netlify from '@astrojs/netlify/edge-functions'; - -export default defineConfig({ - output: 'server', - adapter: netlify(), -}); -``` - ### 在 Edge Functions 中使用中间件 当部署到 Netlify Functions 时,您可以选择使用 Edge Function 来运行 Astro 中间件。 -为了启用这个功能,将 `build.excludeMiddleware` Astro 配置选项设置为 `true`: +为了启用这个功能,将 `edgeMiddleware` Astro 配置选项设置为 `true`: ```js ins={9} // astro.config.mjs @@ -86,10 +69,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - excludeMiddleware: true, - }, + adapter: netlify({ + edgeMiddleware: true, + }), }); ``` @@ -135,10 +117,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - split: true, - }, + adapter: netlify({ + functionPerRoute: true, + }), }); ``` @@ -260,7 +241,7 @@ Netlify Functions 需要 `body` 中的二进制数据被 base64 编码。`@astro import fs from 'node:fs'; -export function get() { +export function GET() { const buffer = fs.readFileSync('../image.jpg'); // Return the buffer directly, @astrojs/netlify will base64 encode the body diff --git a/src/content/docs/zh-cn/guides/integrations-guide/node.mdx b/src/content/docs/zh-cn/guides/integrations-guide/node.mdx index 313927dc40597..3749e89498513 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/node.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/node.mdx @@ -161,7 +161,7 @@ node ./dist/server/entry.mjs 你可以覆盖独立服务器运行的主机和端口,通过在运行时将它们作为环境变量进行传递: ```shell -HOST=0.0.0.0 PORT=3000 node ./dist/server/entry.mjs +HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs ``` #### HTTPS diff --git a/src/content/docs/zh-cn/guides/integrations-guide/preact.mdx b/src/content/docs/zh-cn/guides/integrations-guide/preact.mdx index eabfe909935be..60f64fd583b74 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/preact.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/preact.mdx @@ -120,6 +120,41 @@ export default defineConfig({ 目前,`compat` 选项只适用于 React 库,将代码以 ESM 的形式导出。如果在构建时出现错误,请尝试将该库添加到你的`vite.ssr.noExternal: ['the-react-library']` 的 `astro.config.mjs` 文件中。 ::: +## 选项 + +### 组合多个 JSX 框架 + +当你在同一个项目中使用多个 JSX 框架(React、Preact、Solid)时,Astro 需要确定每个组件应该使用哪个 JSX 框架的转换器(transformation)。如果你只向你的项目中添加了一个 JSX 框架集成,那么就不需要额外的配置。 + +使用 `include`(必填)和 `exclude`(可选)配置选项来指定哪些文件属于哪个框架。为你使用的每个框架提供一个文件或/和文件夹数组。通配符可用于包含多个文件路径。 + +我们建议将每个框架的组件放在同一个文件夹中(例如 `/components/react/` 和 `/components/solid/`),以便更容易地指定你的包含内容,但这不是必需的: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // 启用多个框架来支持所有不同类型的组件。 + // 如果你只使用一个 JSX 框架,则不需要 `include`! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ## 示例 * 在 [Astro Preact 示例](https://github.com/withastro/astro/tree/latest/examples/framework-preact) 中展示了如何在 Astro 项目中使用交互式的 Preact 组件。 diff --git a/src/content/docs/zh-cn/guides/integrations-guide/react.mdx b/src/content/docs/zh-cn/guides/integrations-guide/react.mdx index 4e6b8853aaf28..89bfb85c23ab7 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/react.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/react.mdx @@ -111,6 +111,39 @@ export default defineConfig({ }); ``` +### 组合多个 JSX 框架 + +当你在同一个项目中使用多个 JSX 框架(React、Preact、Solid)时,Astro 需要确定每个组件应该使用哪个 JSX 框架的转换器(transformation)。如果你只向你的项目中添加了一个 JSX 框架集成,那么就不需要额外的配置。 + +使用 `include`(必填)和 `exclude`(可选)配置选项来指定哪些文件属于哪个框架。为你使用的每个框架提供一个文件或/和文件夹数组。通配符可用于包含多个文件路径。 + +我们建议将每个框架的组件放在同一个文件夹中(例如 `/components/react/` 和 `/components/solid/`),以便更容易地指定你的包含内容,但这不是必需的: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // 启用多个框架来支持所有不同类型的组件。 + // 如果你只使用一个 JSX 框架,则不需要 `include`! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ## 故障排除 如需帮助,请查看[Discord](https://astro.build/chat)上的 `#support` 频道。我们友好的支持小组成员将在这里提供帮助! diff --git a/src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx b/src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx index afae06260275c..fdfa512c6ea6b 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/solid-js.mdx @@ -69,6 +69,41 @@ export default defineConfig({ * 💧 客户端水合选项 * 🤝 将框架混合和嵌套在一起的时机 +## 选项 + +### 组合多个 JSX 框架 + +当你在同一个项目中使用多个 JSX 框架(React、Preact、Solid)时,Astro 需要确定每个组件应该使用哪个 JSX 框架的转换器(transformation)。如果你只向你的项目中添加了一个 JSX 框架集成,那么就不需要额外的配置。 + +使用 `include`(必填)和 `exclude`(可选)配置选项来指定哪些文件属于哪个框架。为你使用的每个框架提供一个文件或/和文件夹数组。通配符可用于包含多个文件路径。 + +我们建议将每个框架的组件放在同一个文件夹中(例如 `/components/react/` 和 `/components/solid/`),以便更容易地指定你的包含内容,但这不是必需的: + +```js +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // 启用多个框架来支持所有不同类型的组件。 + // 如果你只使用一个 JSX 框架,则不需要 `include`! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + ## 疑难解答 如需帮助,请查看我们在 [Discord](https://astro.build/chat) 上的 `#support` 频道。 我们友好的支持小队成员随时为你提供帮助! diff --git a/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx b/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx index a8b855bc51591..bf09ab30178a9 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx @@ -64,18 +64,12 @@ pnpm astro add vercel 你可以部署到不同的目标: -* `edge`:在[边缘函数](https://vercel.com/docs/concepts/functions/edge-functions)内进行服务端渲染。 * `serverless`:在 [Node.js 函数](https://vercel.com/docs/concepts/functions/serverless-functions)内进行服务端渲染。 * `static`:生成一个遵循 Vercel 输出格式、重定向等的静态网站。 -:::note -部署到边缘函数会有一些[限制](https://vercel.com/docs/concepts/functions/edge-functions#known-limitations)。 Edge 函数的大小不能超过1MB,并且它们不支持原生 Node.js API 等。 -::: - 你可以通过改变导入来切换目标: ```js -import vercel from '@astrojs/vercel/edge'; import vercel from '@astrojs/vercel/serverless'; import vercel from '@astrojs/vercel/static'; ``` @@ -98,7 +92,7 @@ vercel deploy --prebuilt ### Analytics **类型:** `boolean`
-**适用于:** Serverless, Edge, Static
+**适用于:** Serverless, Static
**添加于** `@astrojs/vercel@3.1.0` 你可以通过设置 `analytics: true` 来启用 [Vercel Analytics](https://vercel.com/analytics) (包括 Web Vitals 和 Audiences) 。这将在所有页面中注入 Vercel 的跟踪脚本。 @@ -119,7 +113,7 @@ export default defineConfig({ ### imagesConfig **类型:** `VercelImageConfig`
-**适用于:** Edge, Serverless, Static
+**适用于:** Serverless, Static
**添加于:** `@astrojs/vercel@3.3.0` [Vercel 的图片优化 API](https://vercel.com/docs/concepts/image-optimization) 选项。 查看 [Vercel 的图片优化配置文档](https://vercel.com/docs/build-output-api/v3/configuration#images)以获取支持的参数的完整列表。 @@ -142,7 +136,7 @@ export default defineConfig({ ### imageService **类型:** `boolean`
-**适用于:** Edge, Serverless, Static
+**适用于:** Serverless, Static
**添加:** `@astrojs/vercel@3.3.0` 启用后,在生产中会自动配置并使用由 Vercel Image Optimization API 提供支持的[图像服务](/zh-cn/reference/image-service-reference/) 。在开发中,将使用内置的 Squoosh-based 服务。 @@ -183,7 +177,7 @@ import astroLogo from '../assets/logo.png'; ### includeFiles **类型:** `string[]`
-**适用于:** Edge, Serverless +**适用于:** Serverless 使用此属性来强制将文件与你的函数打包在一起。当你发现缺失文件时,这很有帮助。 @@ -200,10 +194,6 @@ export default defineConfig({ }); ``` -:::note -当为 Edge 构建时,所有依赖项都会被打包在一个文件中以节省空间。不会打包额外的文件。因此,如果你需要一些文件在函数内部,你必须在 includeFiles 中指定它们。 -::: - ### excludeFiles **类型:** `string[]`
@@ -235,10 +225,9 @@ import vercel from '@astrojs/vercel/serverless'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - split: true, - }, + adapter: vercel({ + functionPerRoute: true, + }), }); ``` @@ -277,7 +266,7 @@ export default defineConfig({ `@astrojs/vercel/serverless` 适配器可以根据你代码库中的 Astro 中间件自动创建 Vercel Edge 中间件。 -这是一个选择性功能,需要将 `build.excludeMiddleware` 选项设置为 `true` : +这是一个选择性功能,需要将 `edgeMiddleware` 选项设置为 `true` : ```js // astro.config.mjs @@ -285,10 +274,9 @@ import { defineConfig } from 'astro/config'; import vercel from '@astrojs/vercel'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - excludeMiddleware: true, - }, + adapter: vercel({ + edgeMiddleware: true, + }), }); ``` diff --git a/src/content/docs/zh-cn/guides/markdown-content.mdx b/src/content/docs/zh-cn/guides/markdown-content.mdx index ca1ba5f9c2db9..515350bc91c73 100644 --- a/src/content/docs/zh-cn/guides/markdown-content.mdx +++ b/src/content/docs/zh-cn/guides/markdown-content.mdx @@ -57,61 +57,6 @@ title: Hello, World 📚 阅读更多关于 Astro [基于文件的路由](/zh-cn/core-concepts/routing/)或创建[动态路由](/zh-cn/core-concepts/routing/#动态路由)的选项。 -### 草稿页面 - -`draft: true` 是一个可选的 frontmatter 值,它将标记单个 Markdown 或 MDX 页面或文章为“未发布”。 默认情况下,此页面将是: - -- 排除在网站构建之外 (**不会有页面被构建**) -- 由 [`Astro.glob()`](/zh-cn/reference/api-reference/#astroglob) 返回 (**在文章的列表中可见**) - -```markdown {5} ---- -# src/pages/post/blog-post.md -layout: ../../layouts/BaseLayout.astro -title: 我的博客文章 -draft: true ---- - -这是我的进行中发博客文章 - -这个文章不会被构建成页面。 - -要构建和发布这篇文章: - -- frontmatter 更新成 `draft: false` 或者 -- 完全删除 `draft` 属性 - -但是,这个页面会被任何匹配的`Astro.glob()`请求返回。 -``` - -要将草稿文章排除在文章存档或最新文章列表之外,你可以过滤 `Astro.glob()` 返回的结果: - -```js -const posts = await Astro.glob('../pages/post/*.md'); -const nonDraftPosts = posts.filter((post) => !post.frontmatter.draft); -``` - -#### 启用构建草稿页面 - -要默认启用构建草稿页面,请通过添加 `drafts: true`到 `markdown` 或 `mdx` 集成来更新 `astro.config.mjs`: - -```js title="astro.config.mjs" ins={5, 8} -import { defineConfig } from 'astro/config'; - -export default defineConfig({ - markdown: { - drafts: true, - }, - integrations: [mdx({ - drafts: true, - })], -}); -``` - -:::tip -你也可以在运行 `astro build` 时传递 `--drafts` 参数来构建草稿页面! -::: - ## Markdown 功能 Astro 在使用 Markdown 和 MDX 文件时提供了一些额外的内置 Markdown 功能。 @@ -181,7 +126,7 @@ title: My page of content 添加 Astro [MDX 集成](/zh-cn/guides/integrations-guide/mdx/)可以使用 JSX 变量、表达式和组件来增强你的 Markdown 编写体验。 -它还为标准 MDX 添加了额外的功能,包括对 [MDX 中的 Markdown 样式 frontmatter](https://mdxjs.com/guides/frontmatter/)的支持。 这允许你使用 Astro 的大多数内置 Markdown 功能,例如 [frontmatter `layout`](#frontmatter-layout) 属性和 [草稿页面](#草稿页面) 的设置。 +它还为标准 MDX 添加了额外的功能,包括对 [MDX 中的 Markdown 样式 frontmatter](https://mdxjs.com/guides/frontmatter/)的支持。 这允许你使用 Astro 的大多数内置 Markdown 功能,例如 [frontmatter `layout`](#frontmatter-layout) 属性。 `.mdx` 文件必须使用 [MDX 语法](https://mdxjs.com/docs/what-is-mdx/#mdx-syntax)编写,而不是 Astro 的 HTML 语法。 diff --git a/src/content/docs/zh-cn/guides/middleware.mdx b/src/content/docs/zh-cn/guides/middleware.mdx index a161b0110cae0..2bf85b278fb2e 100644 --- a/src/content/docs/zh-cn/guides/middleware.mdx +++ b/src/content/docs/zh-cn/guides/middleware.mdx @@ -44,7 +44,7 @@ const data = Astro.locals; ```ts // src/middleware.ts -import { defineMiddleware } from "astro/middleware"; +import { defineMiddleware } from "astro:middleware"; // `context` 和 `next` 已自动进行类型定义 export const onRequest = defineMiddleware((context, next) => { @@ -135,7 +135,7 @@ export const onRequest = async (context, next) => { 可以使用 [`sequence()`](#sequence) 按指定顺序连接多个中间件: ```js title="src/middleware.js" -import { sequence } from "astro/middleware"; +import { sequence } from "astro:middleware"; async function validation(_, next) { console.log("验证请求"); diff --git a/src/content/docs/zh-cn/guides/rss.mdx b/src/content/docs/zh-cn/guides/rss.mdx index 1806351a382c6..46bc88dff6847 100644 --- a/src/content/docs/zh-cn/guides/rss.mdx +++ b/src/content/docs/zh-cn/guides/rss.mdx @@ -46,7 +46,7 @@ Astro 支持为博客和其他内容网站快速,自动的 RSS 提要生成。 ```js title="src/pages/rss.xml.js" import rss from '@astrojs/rss'; -export function get(context) { +export function GET(context) { return rss({ // 输出的 xml 中的``字段 title: 'Buzz’s Blog', @@ -78,7 +78,7 @@ export function get(context) { import rss from '@astrojs/rss'; import { getCollection } from 'astro:content'; -export async function get(context) { +export async function GET(context) { const blog = await getCollection('blog'); return rss({ title: 'Buzz’s Blog', @@ -125,7 +125,7 @@ export const collections = { blog }; ```js title="src/pages/rss.xml.js" "pagesGlobToRssItems" "await pagesGlobToRssItems(" import rss, { pagesGlobToRssItems } from '@astrojs/rss'; -export async function get(context) { +export async function GET(context) { return rss({ title: 'Buzz’s Blog', description: 'A humble Astronaut’s guide to the stars', @@ -165,7 +165,7 @@ import sanitizeHtml from 'sanitize-html'; import MarkdownIt from 'markdown-it'; const parser = new MarkdownIt(); -export async function get(context) { +export async function GET(context) { const blog = await getCollection('blog'); return rss({ title: 'Buzz’s Blog', @@ -187,7 +187,7 @@ export async function get(context) { import rss from '@astrojs/rss'; import sanitizeHtml from 'sanitize-html'; -export function get(context) { +export function GET(context) { const postImportResult = import.meta.glob('../posts/**/*.md', { eager: true }); const posts = Object.values(postImportResult); return rss({ diff --git a/src/content/docs/zh-cn/guides/server-side-rendering.mdx b/src/content/docs/zh-cn/guides/server-side-rendering.mdx index be7bb661ee611..0b05fda63c351 100644 --- a/src/content/docs/zh-cn/guides/server-side-rendering.mdx +++ b/src/content/docs/zh-cn/guides/server-side-rendering.mdx @@ -171,7 +171,7 @@ export const prerender = true; ```js title="src/pages/myendpoint.js" {1} export const prerender = true; -export async function get() { +export async function GET() { return { body: JSON.stringify({ message: `这是我的静态端点` }), }; @@ -185,7 +185,7 @@ export async function get() { ```js title="src/pages/randomnumber.js" {1} export const prerender = false; -export async function get() { +export async function GET() { let number = Math.random(); return { body: JSON.stringify({ number, message: `这是一个随机数: ${number}` }), diff --git a/src/content/docs/zh-cn/guides/styling.mdx b/src/content/docs/zh-cn/guides/styling.mdx index 587c1932265f2..112ec4241fe04 100644 --- a/src/content/docs/zh-cn/guides/styling.mdx +++ b/src/content/docs/zh-cn/guides/styling.mdx @@ -37,11 +37,11 @@ Astro `<style>` 标签内的 CSS 规则**默认自动限定范围**。作用域 编译为: ```astro <style> - h1:where(.astro-HHNQFKH6) { + h1[data-astro-cid-hhnqfkh6] { color: red; } - .text:where(.astro-HHNQFKH6) { + .text[data-astro-cid-hhnqfkh6] { color: blue; } </style> @@ -153,7 +153,8 @@ import MyComponent from "../components/MyComponent.astro" <MyComponent class="red">这将是红色!</MyComponent> ``` -这种模式可以让你直接给子组件添加样式。Astro 会自动将父组件的作用域类名(例如 `astro-HHNQFKH6`)通过 `class` 属性传递给子组件,使得子组件也在父组件的作用域中。 +这种模式可以让你直接给子组件添加样式。Astro 会自动将父组件的作用域类名(例如 `astro-hhnqfkh6`)通过 `class` 属性传递给子组件,使得子组件也在父组件的作用域中。 +注意,这种模式仅在你的 [`scopedStyleStrategy` 选项](/zh-cn/reference/configuration-reference/#scopedstylestrategy) 为 `'where'` 或 `'class'` 时才有效。 :::note[父组件的作用域类名] 由于 `class` 属性包含了子组件在父组件的作用域中,因此父组件的样式可以传递到子组件中。为了避免这种情况,确保在子组件中使用唯一的类名。 @@ -525,24 +526,36 @@ Astro 中的 Svelte 也完全按照预期工作。[Svelte Styling Docs][svelte-s ### 打包控制 -当 Astro 构建您的网站以进行生产部署时,它会将您的 CSS 样式组合成块。您网站上的每个页面都是一个独立的块,此外,多个页面共享的 CSS 样式会被进一步拆分为自己的块,以便重复使用。 +当 Astro 为你的网站构建生产部署时,它会将你的 CSS 压缩并合并到 chunks 中。你网站上的每个页面都有自己的 chunk,此外,多个页面之间共享的 CSS 还会被进一步拆分为自己的 chunk 以供重用。 -在每个 HTML 文件中,都会添加 `<link rel="stylesheet">` 标签,而每个页面所需要的块也会对应一个该标签。 +然而,当你有多个页面共享样式时,一些共享的 chunks 可能会变得非常小。如果它们都被单独发送,那么将会导致许多样式表请求,并影响网站的性能。因此,默认情况下,Astro 仅将 HTML 中大小超过 4kB 的样式表链接为 `<link rel="stylesheet">` 标签,而将较小的样式表内联到 `<style type="text/css">` 中。这种方法在额外请求的数量和可以在页面之间缓存的 CSS 量之间提供了一个平衡。 -具有大量页面和许多不同共享样式的网站可能会导致许多样式表请求,从而影响网站的性能。你可以通过配置 `inlineStylesheets` 选项,将(最小化的)样式表放入 `<style>` 标记中,而不是从外部请求它们,从而减少样式表请求的数量。 +你可以使用 `assetsInlineLimit` vite 构建选项来配置样式表在多大的情况下会被链接到外部(以字节为单位)。请注意,此选项也会影响内联的脚本和图像。 + +```js +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + vite: { + build: { + assetsInlineLimit: 1024, + } + }; +}); +``` + +如果你希望所有项目样式都保持外部样式表,可以配置 `inlineStylesheets` 构建选项。 ```js import { defineConfig } from 'astro/config'; export default defineConfig({ build: { - inlineStylesheets: 'auto' + inlineStylesheets: 'never' } }); ``` -`'auto'` 选项只会将小于 `vite.build.assetsInlineLimit` 阈值的样式表内联,以减少对较小样式表的请求次数。。而较大的样式表,比如被所有页面用到的全局样式表,仍然会从外部获取并缓存。该选项可在加载的样式表数量和在页面中缓存的样式之间取得平衡。 - 你也可以将该选项设置为 `'always'` ,这样就可以内联所有的样式表了。 ## 高级 diff --git a/src/content/docs/zh-cn/guides/troubleshooting.mdx b/src/content/docs/zh-cn/guides/troubleshooting.mdx index 5e544a2bcd88d..de8cb35326c5f 100644 --- a/src/content/docs/zh-cn/guides/troubleshooting.mdx +++ b/src/content/docs/zh-cn/guides/troubleshooting.mdx @@ -199,7 +199,7 @@ console.log(sum(2, 2)); ```astro {2,7} --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const sum = (a, b) => a + b; --- @@ -211,7 +211,7 @@ const sum = (a, b) => a + b; ```astro {2,7-9} --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const sum = (a, b) => a + b; const answer = sum(2, 4); --- diff --git a/src/content/docs/zh-cn/guides/upgrade-to/v3.mdx b/src/content/docs/zh-cn/guides/upgrade-to/v3.mdx new file mode 100644 index 0000000000000..d4e63213a52d6 --- /dev/null +++ b/src/content/docs/zh-cn/guides/upgrade-to/v3.mdx @@ -0,0 +1,630 @@ +--- +title: 升级到 Astro v3 +description: 如何将你的项目升级到 Astro 的最新版本 (v3.0)。 +i18nReady: true +--- +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' +import FileTree from '~/components/FileTree.astro' + + +本指南将帮助你从 Astro v2 迁移到 Astro v3。 + +需要将旧项目升级到 v2 吗?请参阅我们的 [旧版本迁移指南](/zh-cn/guides/upgrade-to/v2/)。 + +## 升级 Astro + +使用你的包管理器将项目的 Astro 版本更新到最新版本。如果你正在使用 Astro 集成,请同时将其更新到最新版本。 + +<PackageManagerTabs> + <Fragment slot="npm"> + ```shell + # 升级到 Astro v3.x + npm install astro@latest + + # 示例:升级 React 和 Tailwind 集成 + npm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> + <Fragment slot="pnpm"> + ```shell + # 升级到 Astro v3.x + pnpm install astro@latest + + # 示例:升级 React 和 Tailwind 集成 + pnpm install @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> + <Fragment slot="yarn"> + ```shell + # 升级到 Astro v3.x + yarn add astro@latest + + # 示例:升级 React 和 Tailwind 集成 + yarn add @astrojs/react@latest @astrojs/tailwind@latest + ``` + </Fragment> +</PackageManagerTabs> + +:::note[需要继续吗?] +升级 Astro 到最新版本后,你可能不需要对你的项目做任何更改! + +但是,如果你注意到错误或意外的行为,请检查下面的内容,看看有什么变化可能需要在你的项目中更新。 +::: + +## Astro v3.0 实验性标志已移除 + +从 `astro.config.mjs` 中移除以下实验性标志: + +```js del={5-8} +// astro.config.mjs +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + experimental: { + assets: true, + viewTransitions: true, + }, +}) +``` + +这些特性现在默认可用: + +- 视图过渡动画用于动画页面过渡和持久化组件。如果你使用此实验性标志,请查看 [视图过渡动画 API 重大更改及升级建议](/zh-cn/guides/view-transitions/#从-v2x-升级到-v30)。 +- 新的图像服务 API `astro:assets` 用于在 Astro 中使用图像,包括新的 `<Image />` 组件和 `getImage()` 函数。**无论你是否使用此实验性标志**,请阅读详细的 [图像升级建议](/zh-cn/guides/images/#从-v2x-升级到-v30) ,以了解这可能如何影响你的项目。 + +在 3.0 博客文章阅读更多关于这两个令人兴奋的功能和更多其他内容! + +## Astro v3.0 破坏性更改 + +Astro v3.0 包含了一些破坏性更改,以及一些之前已经弃用的功能的移除。如果你的项目在升级到 v3.0 后无法正常工作,请查看本指南,了解所有破坏性更改的概述以及如何更新你的代码库的说明。 + +请查看 [更新日志](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) 以获取完整的发布说明。 + +### 移除:对 Node 16 的支持 + +Node 16 计划在 2023 年 9 月达到其生命周期终点。 + +Astro v3.0 完全放弃对 Node 16 的支持,以便所有 Astro 用户都能利用 Node 的更现代化的功能。 + +#### 我应该怎么做? + + 检查你的开发环境和部署环境是否都使用**Node `18.14.1` 或更高版本**。 + +1. 使用以下命令检查 Node 本地版本: + + ```sh + node -v + ``` + +2. 查看你的 [部署环境](/zh-cn/guides/deploy/) 的文档,以确认它们是否支持 Node 18。 + + 你可以在仪表板配置设置或 `.nvmrc` 文件中为你的 Astro 项目指定 `Node 18.14.1`。 + +```bash title=".nvmrc" +18.14.1 +``` +### 移除:对 TypeScript 4 的支持 + +在 Astro v2.x 中,`tsconfig.json` 预设包含对 TypeScript 4.x 和 5.x 的支持。 + +Astro v3.0 更新了 `tsconfig.json` 预设,只支持 TypeScript 5.x。Astro 现在假设你使用 TypeScript 5.0(2023 年 3 月),或者你的编辑器包含它(例如 VS Code 1.77)。 + +#### 我应该怎么做? + +如果你本地安装了 TypeScript,请更新到至少 v5.0。 + +```bash +npm install typescript@latest --save-dev +``` + +### 移除:`@astrojs/image` + +在 Astro v2.x 中,Astro 提供了一个官方的图像集成,其中包括 Astro `<Image />` 和 `<Picture />` 组件。 + +Astro v3.0 完全从代码库中删除了这个集成。Astro 图像的新解决方案是内置的图像服务 API:`astro:assets`。 + +#### 我应该怎么做? + +移除 `@astrojs/image` 集成。你不仅需要卸载集成,还需要更新或删除任何导入语句和现有的 `<Image />` 和 `<Picture />` 组件。你可能还需要配置一个首选的默认图像处理服务。 + +你可以在我们的 [图像指南](/zh-cn/guides/images/#移除-astrojsimage) 中找到完整的、逐步的删除旧图像集成的说明。 + +迁移 `astro:assets` 还将带来一些你现在可能希望使用的新的图像选项和功能。请参阅完整的 [v3.0 图像升级建议](/zh-cn/guides/images/#从-v2x-升级到-v30) 了解完整的详情! + +```js del={3,7} +// astro.config.mjs +import { defineConfig } from 'astro/config'; +import image from '@astrojs/image'; + +export default defineConfig({ + integrations: [ + image(), + ] +}) +``` + +### 移除:`<Markdown />` 组件 + +在 Astro v1.x 中,Astro 废弃了 `<Markdown />` 组件,并将其移动到了一个外部包中。 + +Astro v3.0 完全删除了 `@astrojs/markdown-component` 包。Astro 的 `<Markdown />` 组件将不再在你的项目中工作。 + +#### 我应该怎么做? + +移除所有的 `@astrojs/markdown-component` 实例。 + +```astro del={2} title="src/components/MyAstroComponent.astro" +--- +import Markdown from '@astrojs/markdown-component'; +--- +``` + +要继续在你的代码中使用类似的 `<Markdown />` 组件,请考虑使用 [社区集成](https://astro.build/integrations/),例如 [`astro-remote`](https://github.com/natemoo-re/astro-remote)。请根据集成的文档更新你的 `<Markdown />` 组件导入和属性。 + +否则,请删除所有对导入 Astro 的 `<Markdown />` 组件及其本身的引用。你需要直接将你的内容重写为 HTML,或者从 `.md` 文件中[导入 Markdown](/zh-cn/guides/markdown-content/#导入-markdown)。 + +### 移除:已废弃的 1.x API + +在 Astro v1.x 中,Astro 废弃了配置选项以及脚本/样式 `global` 和 `hoist` 属性类型。这些被保留是为了向后兼容。 + +Astro v3.0 完全删除了这些已弃用的 API。它们不能再在你的 Astro 项目中使用。 + +#### 我应该怎么做? + +如果你正在继续使用 v1.x API,请改用每个功能的新 API: + +- 废弃的配置选项:请参阅 [0.26 迁移指南](/zh-cn/guides/upgrade-to/v1/#new-configuration-api) +- 废弃的脚本/样式类型:请参阅 [0.26 迁移指南](/zh-cn/guides/upgrade-to/v1/#new-default-script-behavior) + +### 移除: 内容集合 schema 中来自 `astro:content` 的 `image` + +在 Astro v2.x 中,内容集合 API 废弃了来自 `astro:content` 的 `image` 导出,用于在你的内容集合 schema 中使用。 + +Astro v3.0 完全删除了这个导出。 + +#### 我应该怎么做? + +如果你正在使用 `astro:content` 中废弃的 `image()`,请删除它,因为它已经不存在了。请通过 [来自 `schema` 的 `image` 帮助程序](/zh-cn/guides/images/#更新内容集合模式) 来验证图像。 + + ```ts title="astro.config.mjs" del={1} ins={2} "({ image })" +import { defineCollection, z, image } from "astro:content"; +import { defineCollection, z } from "astro:content"; + + defineCollection({ + schema: ({ image }) => + z.object({ + image: image(), + }), +}); +``` + +### 移除:pre-0.14 Shiki 主题名称 + +在 Astro v2.x 中,一些 Shiki 主题名称已被重命名,但原始名称仍保留了向后兼容性。 + +Astro v3.0 删除了原始名称,而采用了重命名的主题名称。 + +#### 我应该怎么做? + +如果你的 Astro 项目使用了以下任何主题,请将它们重命名为更新后的名称: + +- `material-darker` -> `material-theme-darker` +- `material-default` -> `material-theme` +- `material-lighter` -> `material-theme-lighter` +- `material-ocean` -> `material-theme-ocean` +- `material-palenight` -> `material-theme-palenight` + +### 移除:`class:list` 功能 + +在 Astro v2.x 中,[`class:list` 指令](/zh-cn/reference/directives-reference/#classlist) 使用了一个受 [`clsx`](https://github.com/lukeed/clsx) 启发的自定义实现,其中包含一些额外的功能,如去重和 `Set` 支持。 + +Astro v3.0 现在直接使用 `clsx` 来处理 `class:list`,它不支持去重和 `Set` 值。 + +#### 我应该怎么做? + +将传递给 `class:list` 指令的任何 `Set` 元素替换为普通数组。 +```astro title="src/components/MyAstroComponent.astro" del={4} ins={5} +<Component class:list={[ + 'a', + 'b', + new Set(['c', 'd']) + ['c', 'd'] +]} /> +``` + +### 移除:将 `class:list` 作为 prop 传递 + +在 Astro v2.x 中,[`class:list` 的值](/zh-cn/reference/directives-reference/#classlist) 通过 [`Astro.props['class:list']`](/zh-cn/reference/api-reference/#astroprops) 传递给组件。 + +Astro v3.0 将 `class:list` 的值标准化为字符串,然后通过 `Astro.props['class']` 发送给组件。 + +#### 我应该怎么做? + +移除任何期望接收 `class:list` prop 的代码。 + +```astro title="src/components/MyAstroComponent.astro" del={2,3,7} ins={4,8} "classList" "'class:list': classList" +--- +import { clsx } from 'clsx'; +const { class: className, 'class:list': classList } = Astro.props; +const { class: className } = Astro.props; +--- +<div + class:list={[className, classList]} + class:list={[className]} +/> +``` + +### 移除:对于 camelCase CSS 变量的 kebab-case 转换 + +在 Astro v2.x 中,传递给 `style` 属性的 camelCase [CSS 变量](/zh-cn/guides/styling/#css-变量) 会被渲染为 camelCase(如写入的那样)和 kebab-case(保留向后兼容性)。 + +Astro v3.0 移除了这些 camelCase CSS 变量名称的 kebab-case 转换,只有原始的 camelCase CSS 变量被渲染。 + +```astro "my-value" +--- +// src/components/MyAstroComponent.astro +const myValue = "red" +--- +<!-- 输入 --> +<div style={{ "--myValue": myValue }}></div> + +<!-- 输出 (Astro 2.x) --> +<div style="--my-value:var(--myValue);--myValue:red"></div> +<!-- 输出 (Astro 3.0) --> +<div style="--myValue:red"></div> +``` + +#### 我应该怎么做? + +如果你依靠 Astro 来转换你的样式中的 kebab-case,请更新你现有的样式为 camelCase,以防止丢失样式。例如: + +```astro del={3} ins={4} title="src/components/MyAstroComponent.astro" +<style> + div { + color: var(--my-value); + color: var(--myValue); + } +</style> +``` + +### 移除:自动展平 `getStaticPaths()` 的返回值 + +在 Astro v2.x 中,`getStaticPaths()` 的返回值会自动展平,以允许返回一个二维数组而不会出错。 + +Astro v3.0 移除了对 `getStaticPaths()` 返回值的自动展平。 + +#### 我应该怎么做? + +如果你返回的是一个二维数组而不是一个(预期的)_一维对象数组_,则应该使用 `.flatMap` 和 `.flat` 来确保你返回的是展平的一维数组。 + +如果你需要更新代码,Astro 将抛出一个错误消息,指出 `getStaticPath()` 的返回值必须是一个对象数组。 + +### 移动:`astro check` 现在需要一个外部包 + +在 Astro v2.x 中,默认情况下包含了 [`astro check`](/zh-cn/reference/cli-reference/#astro-check),并且它的依赖项被打包在 Astro 中。这意味着无论你是否使用 `astro check`,都会有一个更大的包。这也阻止你对 TypeScript 和 Astro 语言服务器的版本进行控制。 + +Astro v3.0 将 `astro check` 命令从 Astro 核心中移出,并且现在需要一个外部包 `@astrojs/check`。此外,你必须在你的项目中安装 `typescript` 来使用 `astro check` 命令。 + +#### 我应该怎么做? + +在升级 Astro v3.0 后运行 `astro check` 命令,并按照提示安装所需的依赖项,或者手动将 `@astrojs/check` 和 `typescript` 安装到你的项目中。 + +### 废弃:`build.excludeMiddleware` 和 `build.split` + +在 Astro v2.x 中,`build.excludeMiddleware` 和 `build.split` 用于在 SSR 模式下使用适配器时更改特定文件的产出方式。 + +Astro v3.0 用新的 [SSR 适配器配置选项](/zh-cn/guides/integrations-guide/#官方集成) 替换了这些构建配置选项,以执行相同的任务:`edgeMiddleware` 和 `functionPerRoute`。 + +#### 我应该怎么做? + +更新 Astro 配置文件,直接在适配器配置中使用新的选项。 + +```js title="astro.config.mjs" del={5-7} ins={9} +import { defineConfig } from "astro/config"; +import vercel from "@astrojs/vercel/serverless"; + +export default defineConfig({ + build: { + excludeMiddleware: true + }, + adapter: vercel({ + edgeMiddleware: true + }), +}); +``` + +```js title="astro.config.mjs" del={5-7} ins={9} +import { defineConfig } from "astro/config"; +import netlify from "@astrojs/netlify/functions"; + +export default defineConfig({ + build: { + split: true + }, + adapter: netlify({ + functionPerRoute: true + }), +}); +``` + +### 废弃:`markdown.drafts` + +在 Astro v2.x 中,`markdown.drafts` 配置允许你在运行开发服务器时拥有草稿页面,但在生产环境中不会构建。 + +Astro v3.0 废弃了这个功能,而是使用内容集合的方法来处理草稿页面,通过手动过滤来实现,这样可以更好地控制这个功能。 + +#### 我应该怎么做? + +为了继续将你项目中的某些页面标记为草稿,请 [迁移到内容集合](/zh-cn/guides/content-collections/#从基于文件的路由迁移),并使用 `draft: true` frontmatter 属性 [手动过滤页面](/zh-cn/guides/content-collections/#筛选集合查询)。 + +### 废弃:在端点(endpoints)中返回简单对象 + +在 Astro v2.x 中,端点(endpoints)可以返回一个简单的对象,它会被转换为一个 JSON 响应。 + +Astro v3.0 废弃了这种行为,而是直接返回一个 `Response` 对象。 + +#### 我应该怎么做? + +更新你的端点(endpoints),直接返回一个 `Response` 对象。 + +```ts title="endpoint.json.ts" del={2} ins={3} +export async function GET() { + return { body: { "title": "Bob's blog" }}; + return new Response(JSON.stringify({ "title": "Bob's blog" })); +} +``` + +如果你确实需要保留以前的格式,你可以使用 `ResponseWithEncoding` 对象,但它会在将来被弃用。 + +```ts title="endpoint.json.ts" del={2} ins={3} +export async function GET() { + return { body: { "title": "Bob's blog" } }; + return new ResponseWithEncoding({ body: { "title": "Bob's blog" }}); +} +``` + +### 默认值改变:端口 `3000` + +在 Astro v2.x 中,默认情况下,Astro 运行在 `3000` 端口上。 + +Astro v3.0 将 [默认端口](/zh-cn/reference/cli-reference/#--port-number) 更改为 `4321`。🚀 + +#### 我应该怎么做? + +更新任何现有的引用 `localhost:3000`,例如在测试或在你的 `README` 中,以反映新的端口 `localhost:4321`。 + +### 默认值改变:import.meta.env.BASE_URL `trailingSlash` + +在 Astro v2.x 中,除非 [`trailingSlash`](/zh-cn/reference/configuration-reference/#trailingslash) 被设置为 `never`,否则 `import.meta.env.BASE_URL` 总是被设置成以斜杠 `/` 结尾的 [`base`](/zh-cn/reference/configuration-reference/#base)。也就是说默认情况下如果 `base` 不是以斜杠结尾的,Astro 会帮你添加一个。 + +Astro v3.0 中的 `import.meta.env.BASE_URL` 默认情况下不再给 `base` 添加斜杠,也不会在设置 `trailingSlash: "ignore"` 时添加斜杠。`trailingSlash: "always"` 和 `trailingSlash: "never"` 的行为保持不变。 + +#### 我应该怎么做? + +如果你的 `base` 已经以斜杠结尾,或你的 `trailingSlash` 设置为 `always` 或 `never`,则不需要更改。 + +如果你的 `base` 不以斜杠结尾 **并且** 你希望 `import.meta.env.BASE_URL` 与以前保持一致,请在 `base` 后添加一个斜杠。 + +```js title="astro.config.mjs" del={4} ins={5} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + base: 'my-base', + base: 'my-base/', +}); +``` + +### 默认值改变:`compressHTML` + +在 Astro v2.x 中,只有当 [`compressHTML`](/zh-cn/reference/configuration-reference/#compresshtml) 明确设置为 `true` 时,Astro 才会压缩你发出的 HTML。默认值曾经是 `false`。 + +Astro v3.0 现在默认压缩产出的 HTML。 + +#### 我应该怎么做? + +你可以从你的配置中删除 `compressHTML: true`,因为这是新的默认行为。 + +```js title="astro.config.mjs" del={4} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + compressHTML: true +}) +``` + +你现在必须设置 `compressHTML: false` 来禁用 HTML 压缩。 + +### 默认值改变:`scopedStyleStrategy` + +在 Astro v2.x 中,[`scopedStyleStrategy`](/zh-cn/reference/configuration-reference/#scopedstylestrategy) 的默认值是 `"where"`。 + +Astro v3.0 引入了一个新的默认值:`"attribute"`。现在默认情况下,样式使用 `data-*` 属性。 + +#### 我应该怎么做? + +为了保留你项目的当前 [样式作用域](/zh-cn/guides/styling/#作用域样式),请修改配置文件为以前的默认值: + +```js title="astro.config.mjs" ins={4} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + scopedStyleStrategy: "where" +}) +``` + +### 默认值改变:`inlineStyleSheets` + +在 Astro v2.x 中,默认情况下,所有项目样式表都作为 `link` 标签输出。你可以通过设置为 `"always"` 使它们总是内联到 `<style>` 标签中,或者设置为 `"auto"` 再通过 [`build.inlineStylesheets`](/zh-cn/reference/configuration-reference/#buildinlinestylesheets) 设置项来仅内联小于某个大小的样式表。默认设置曾经为 `"never"`。 + +Astro v3.0 将 `inlineStylesheets` 的默认值更改为 `"auto"`。默认情况下小于 `ViteConfig.build.assetsInlineLimit`(默认值:4kb)的样式表被内联,其他项目样式将以外部样式表的形式输出。 + +#### 我应该怎么做? +如果你想保留你项目的当前行为,请将 `build.inlineStylesheets` 设置为以前的默认值 `"never"`: + +```js title="astro.config.mjs" ins={4-6} +import { defineConfig } from "astro/config"; + +export default defineConfig({ + build: { + inlineStylesheets: "never" + } +}) +``` + +### 默认值改变:图像服务 + +在 Astro v2.x 中,Squoosh 是[默认的图像处理服务](/zh-cn/guides/images/#默认图像服务)。 + +Astro v3.0 将 Sharp 作为默认的图像处理服务,并提供了一个配置选项来使用 Squoosh。 + +#### 我应该怎么做? + +如果你希望继续使用 Squoosh 来转换你的图像,请使用以下配置更新你的配置: + +```ts title="astro.config.mjs" ins={4-6} +import { defineConfig, squooshImageService } from "astro/config"; + +export default defineConfig({ + image: { + service: squooshImageService(), + } +}) +``` + +### 修改:HTTP 请求方法案例 + +在 Astro v2.x 中,[HTTP 请求方法](/zh-cn/core-concepts/endpoints/#http-方法) 使用小写函数名称编写:`get`、`post`、`put`、`all` 和 `del`。 + +Astro v3.0 使用大写函数名称,使用 `DELETE` 而不是 `del`。 + +#### 我应该怎么做? + +重命名所有的函数名为它们的大写形式: + +- `get` 改为 `GET` +- `post` 改为 `POST` +- `put` 改为 `PUT` +- `all` 改为 `ALL` +- `del` 改为 `DELETE` + +```js title="endpoint.ts" del={1} ins={2} +export function get() { +export function GET() { + return new Response(JSON.stringify({ "title": "Bob's blog" })); +} +``` + +### 修改:多个 JSX 框架配置 + +在 Astro v2.x 中,你可以在同一个项目中使用多个 JSX 框架集成(React、Solid、Preact)而不需要指定哪些文件属于哪个框架。 + +Astro v3.0 现在要求你在有多个 JSX 框架集成时,使用新的 `include` 和 `exclude` 集成配置选项来指定你的文件使用哪个框架。这使得 Astro 更好地支持单框架使用,以及 React Fast Refresh 等高级功能。 + +#### 我应该怎么做? + +如果你在同一个项目中使用多个 JSX 框架集成,请将 `include`(和可选的 `exclude`)设置为文件或文件夹的路径数组。可用通配符来包含多个文件路径。 + +我们建议将常见的框架组件放在同一个文件夹中(例如 `/components/react/` 和 `/components/solid/`),以便更容易地指定你的包含内容,但这不是必需的: + +```js ins={13,16,19} +import { defineConfig } from 'astro/config'; +import preact from '@astrojs/preact'; +import react from '@astrojs/react'; +import svelte from '@astrojs/svelte'; +import vue from '@astrojs/vue'; +import solid from '@astrojs/solid-js'; + +export default defineConfig({ + // 启用多个框架来支持所有不同类型的组件。 + // 如果你只使用一个 JSX 框架,则不需要 `include`! + integrations: [ + preact({ + include: ['**/preact/*'], + }), + react({ + include: ['**/react/*'], + }), + solid({ + include: ['**/solid/*'], + }), + ], +}); +``` + +### 修改:`Astro.cookies.get(key)` 可以返回 `undefined` + +在 Astro v2.x 中,[`Astro.cookies.get(key)`](/zh-cn/reference/api-reference/#astrocookies) 即使 cookie 不存在也会返回一个 [`AstroCookie` 对象](/zh-cn/reference/api-reference/#astrocookie)。要检查它是否存在,你需要使用 `Astro.cookies.has(key)`。 + +Astro v3.0 中,如果 cookie 不存在,`Astro.cookies.get(key)` 会返回 `undefined`。 + +#### 我应该怎么做? + +这个修改不会影响任何在调用 `Astro.cookies.get(key)` 之前用 `Astro.cookies.has(key)` 检查 cookie 是否存在的代码,但现在不再需要检查。 + +你可以安全的删除任何使用 `has()` 来检查 cookie 是否存在的代码: + +```js del={1-3} ins={5-7} +if (Astro.cookies.has(id)) { + const id = Astro.cookies.get(id)!; +} + +const id = Astro.cookies.get(id); +if (id) { +} +``` + +### 修改:以编程方式运行 Astro CLI + +在 Astro v2.x 中,`"astro"` 包的入口点直接导出并运行 Astro CLI。在实践中不建议以这种方式运行 Astro。 + +Astro v3.0 从入口点中删除了 CLI,并导出了一组新的实验性 JavaScript API,包括 `dev()`、`build()`、`preview()` 和 `sync()`。 + +#### 我应该怎么做? + +要 [以编程方式运行 Astro CLI](/zh-cn/reference/cli-reference/#高级-api实验性),请使用新的实验性 JavaScript API: + +```js +import { dev, build } from "astro"; + +// 启动 Astro 开发服务器 +const devServer = await dev(); +await devServer.stop(); + +// 构建 Astro 项目 +await build(); +``` + + +### 修改:内部 Astro API 入口文件导出路径 + +在 Astro v2.x 中,你可以从 `astro/internal/*` 和 `astro/runtime/server/*` 导入内部 Astro API。 + +Astro v3.0 删除了这两个入口文件,而是使用现有的 `astro/runtime/*` 入口文件。此外,还为编译器的运行时代码导出了一个新的 `astro/compiler-runtime`。 + +#### 我应该怎么做? + +这些是 Astro 内部 API 的入口文件,不应该影响你的项目。但如果你确实使用了这些入口文件,请按照下面的说明更新: + +```js del={1,4,10} ins={2,5,11} +import 'astro/internal/index.js'; +import 'astro/runtime/server/index.js'; + +import 'astro/server/index.js'; +import 'astro/runtime/server/index.js'; +``` + +```js ins={5} del={4} +import { transform } from '@astrojs/compiler'; + +const result = await transform(source, { + internalURL: 'astro/runtime/server/index.js', + internalURL: 'astro/compiler-runtime', + // ... +}); +``` + + + +## 已知问题 + +目前没有已知的问题。 diff --git a/src/content/docs/zh-cn/guides/view-transitions.mdx b/src/content/docs/zh-cn/guides/view-transitions.mdx index ba3e56061c535..920eb3025d089 100644 --- a/src/content/docs/zh-cn/guides/view-transitions.mdx +++ b/src/content/docs/zh-cn/guides/view-transitions.mdx @@ -1,52 +1,56 @@ --- -title: 视图过渡动画 (实验性) +title: 视图过渡动画 description: >- - 如何在你的 Astro 网站中开启实验性的视图过渡动画。 + 在 Astro 中通过视图过渡动画实现页面之间的无缝导航。 i18nReady: true --- import Since from '~/components/Since.astro' -Astro 项目中对于**可选择的、每个页面的视图过渡动画**的支持可以通过实验性标志启用。视图过渡动画在更新页面内容时不会触发浏览器的正常全页导航刷新,并且提供了页面之间无缝动画切换的效果。 +Astro 仅需几行代码就可以支持**可选择的,每个页面的视图过渡动画**。视图过渡动画可以在不刷新浏览器的情况下更新页面内容,并在页面之间提供无缝的动画效果。 -Astro 提供了一个 `<ViewTransitions />` 路由组件,可以添加到单个页面的 `<head>` 中,用于控制页面在导航到另一个页面时的过渡效果。这提供了一种轻量的客户端路由,能够拦截导航并让你去自定义页面之间的过渡动画。而将该组件添加到可复用的 `.astro` 组件中,比如常用的头部或布局组件,可以实现整个站点(SPA 模式)的动画页面过渡效果。 +Astro 提供了一个 `<ViewTransitions />` 路由组件,可以添加到单个页面的 `<head>` 中,以控制页面在导航到另一个页面时的过渡效果。它提供了一个轻量级的客户端路由器,[拦截导航](#客户端导航流程) 并允许你自定义页面之间的过渡效果。 -Astro 的视图过渡动画支持是基于新的 [视图过渡动画](https://developer.chrome.com/docs/web-platform/view-transitions/) 浏览器 API,并包括以下功能: +将此组件添加到一个可复用的 `.astro` 组件中,例如公共头部或布局组件,以便 [在整个站点上实现动画页面过渡(SPA 模式)](#整站视图过渡动画spa-模式)。 -- 几种 [内置动画](#内置的动画指令),例如 `slide` 和 `fade`; -- 支持前进和后退导航动画; -- 可完全[自定义过渡动画](#自定义动画)的能力,可以构建自己的动画效果; -- 对于尚未支持视图过渡动画 API 的浏览器,可以[控制回退行为](#回退控制)。 +Astro 的视图过渡动画支持由新的 [View Transitions](https://developer.chrome.com/docs/web-platform/view-transitions/) 浏览器 API 提供,还包括: -:::caution -视图过渡动画是 Astro 2.9 中的实验性功能。在标记为稳定之前,API 可能会发生变化。 -::: +- 一些 [内置的动画选项](#内置动画指令),例如 `fade`、`slide` 和 `none`。 +- 支持前进和后退导航动画; +- 可完全 [自定义过渡动画](#自定义动画) 的能力,可以构建自己的动画效果; +- 用于 [阻止非页面链接的客户端导航](#阻止客户端导航) 的选项。 +- 对于尚未支持视图过渡动画 API 的浏览器,可以 [控制回退行为](#回退控制)。 +- 自动支持 [`prefers-reduced-motion`](#prefers-reduced-motion)。 -## 在项目中启用视图过渡动画 -你可以通过 Astro 配置中的实验性 `viewTransitions` 标志来启用对动画页面过渡效果的支持: +:::note +默认情况下,每个页面都将使用常规的、全页的浏览器导航。你必须选择视图过渡动画,并且可以在每个页面或整个站点上使用它们。 +::: -```js title="astro.config.mjs" ins={4-6} -import { defineConfig } from 'astro/config'; +## 向页面添加视图过渡动画 -export default defineConfig({ - experimental: { - viewTransitions: true - } -}); -``` - -:::note -启用视图过渡动画支持不会自动将整个站点转换为单页应用(SPA)。默认情况下,每个页面仍将使用常规的、全页的浏览器导航。 +通过在每个页面的 `<head>` 中导入和添加 `<ViewTransitions />` 路由组件,可以选择在单个页面上使用视图过渡动画。 -在 Astro 中,通过在每个页面或整个站点上添加 `<ViewTransitions />` 路由组件来添加页面过渡效果。 -::: +```astro title="src/pages/index.astro" ins={2,7} +--- +import { ViewTransitions } from 'astro:transitions'; +--- +<html lang="en"> + <head> + <title>我的主页 + + + +

欢迎来到我的网站!

+ + +``` ## 整站视图过渡动画(SPA 模式) -导入并将 `` 组件添加到你的公共 `` 或共享布局组件中。Astro 将根据旧页面和新页面之间的相似性创建默认的页面动画,并为不支持的浏览器提供回退行为。 +导入 `` 组件并将其添加到公共 `` 或共享布局组件中。Astro 将根据旧页面和新页面之间的相似之处创建默认的页面动画,并为不支持的浏览器提供回退行为。 -下面的示例展示了如何通过导入和添加此组件到 `` Astro 组件来在整个站点上添加视图过渡效果: +下面的示例显示了如何通过导入和添加此组件到 `` Astro 组件中,为不支持的浏览器提供默认的页面导航动画,包括默认的回退控制选项,从而在整个站点上添加 Astro 的默认页面导航动画: ```astro title="components/CommonHead.astro" ins={2,12} --- @@ -55,7 +59,7 @@ import { ViewTransitions } from 'astro:transitions'; - + {title} @@ -63,7 +67,9 @@ import { ViewTransitions } from 'astro:transitions'; ``` -你还可以在每个页面的基础上添加视图过渡效果,即导入 `` 组件,并直接将其放置在页面的 `` 中。 +无需其他配置即可启用 Astro 的默认客户端导航! + +对于更精细的控制,可以在单个元素上使用 [过渡动画指令](#过渡动画指令) 或 [覆盖默认的客户端导航](#preventing-client-side-navigation)。 ## 过渡动画指令 @@ -71,11 +77,11 @@ Astro 会自动为在旧页面和新页面中找到的相应元素并分配一 在你的 `.astro` 组件的页面元素上使用可选的 `transition:*` 指令,以更精确地控制导航期间的页面过渡行为。 -- `transition:name`:允许你覆盖 Astro 的默认元素匹配方式,为一对 DOM 元素[指定过渡动画名称](#命名过渡动画)。 -- `transition:animate`:在用新元素替换旧元素时,允许你通过指定动画类型来覆盖 Astro 的默认动画效果。可以使用 Astro 的 [内置动画指令](#内置的动画指令) 或 [创建自定义动画](#自定义动画)。 +- `transition:name`:允许你覆盖 Astro 的默认元素匹配方式,为一对 DOM 元素 [指定过渡动画名称](#命名过渡动画)。 +- `transition:animate`:在用新元素替换旧元素时,允许你通过指定动画类型来覆盖 Astro 的默认动画效果。可以使用 Astro 的 [内置动画指令](#内置的动画指令) 或 [创建自定义动画](#自定义动画)。 - `transition:persist`: 允许你覆盖 Astro 的默认行为。不同于在导航到另一个页面时用将替换旧元素为新元素的方式,该行为则是在导航到另一个页面时 [保留组件和 HTML 元素的状态](#维持状态)。 -## 命名过渡动画 +### 命名过渡动画 在某些情况下,你可能希望自己对相应的且包含视图过渡动画的元素进行标识,那么你可以使用 `transition:name` 指令为一对元素指定一个名称。 @@ -87,9 +93,9 @@ Astro 会自动为在旧页面和新页面中找到的相应元素并分配一