From f25ae4d776e1e0014a13e1cc4dfcba6a9ae27b16 Mon Sep 17 00:00:00 2001 From: liruifengv Date: Thu, 24 Aug 2023 21:24:25 +0800 Subject: [PATCH 01/57] i18n(zh-cn): uppercase http methods & some update. --- .../docs/en/core-concepts/endpoints.mdx | 2 +- .../docs/zh-cn/core-concepts/endpoints.mdx | 30 ++++++++-------- .../zh-cn/core-concepts/project-structure.mdx | 5 --- .../zh-cn/guides/backend/google-firebase.mdx | 25 +++++++------ .../docs/zh-cn/guides/content-collections.mdx | 2 +- .../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 | 8 ++--- .../guides/integrations-guide/netlify.mdx | 35 +++++-------------- .../zh-cn/guides/integrations-guide/node.mdx | 2 +- .../guides/integrations-guide/vercel.mdx | 34 ++++++------------ 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 +-- .../docs/zh-cn/guides/troubleshooting.mdx | 4 +-- 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 +-- .../docs/zh-cn/reference/api-reference.mdx | 24 ++++++------- .../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 +- .../errors/static-redirect-not-available.mdx | 2 +- .../errors/unsupported-image-format.mdx | 4 +-- .../reference/image-service-reference.mdx | 2 +- src/content/docs/zh-cn/tutorial/1-setup/1.mdx | 8 ++--- .../docs/zh-cn/tutorial/5-astro-api/4.mdx | 2 +- 31 files changed, 99 insertions(+), 139 deletions(-) diff --git a/src/content/docs/en/core-concepts/endpoints.mdx b/src/content/docs/en/core-concepts/endpoints.mdx index f03e7cb7352cf..38aeb0f867825 100644 --- a/src/content/docs/en/core-concepts/endpoints.mdx +++ b/src/content/docs/en/core-concepts/endpoints.mdx @@ -12,7 +12,7 @@ In statically-generated sites, your custom endpoints are called at build time to ## Static File Endpoints To create a custom endpoint, add a `.js` or `.ts` file to the `/pages` directory. The `.js` or `.ts` extension will be removed during the build process, so the name of the file should include the extension of the data you want to create. For example, `src/pages/data.json.ts` will build a `/data.json` endpoint. -Endpoints export a `get` function (optionally `async`) that receives a [context object](/en/reference/api-reference/#endpoint-context) with properties similar to the `Astro` global. It returns an object with a `body`, and Astro will call this at build time and use the contents of the body to generate the file. +Endpoints export a `GET` function (optionally `async`) that receives a [context object](/en/reference/api-reference/#endpoint-context) with properties similar to the `Astro` global. It returns an object with a `body`, and Astro will call this at build time and use the contents of the body to generate the file. ```ts // Example: src/pages/builtwith.json.ts diff --git a/src/content/docs/zh-cn/core-concepts/endpoints.mdx b/src/content/docs/zh-cn/core-concepts/endpoints.mdx index 770eb41438a5f..692061c2f2c29 100644 --- a/src/content/docs/zh-cn/core-concepts/endpoints.mdx +++ b/src/content/docs/zh-cn/core-concepts/endpoints.mdx @@ -13,11 +13,11 @@ Astro 允许你创建自定义端点来提供任何类型的数据。你可以 要想要创建自定义端点,请将 `.js` 或 `.ts` 文件添加到 `/pages` 目录。`.js` 或 `.ts` 这样的扩展名将在构建过程中被删除,因此文件名中应包含你要创建的数据的扩展名。例如,文件 `src/pages/data.json.ts` 将被构建为 API 端点 `/data.json`。 -端点导出一个 `get` 函数(可选的以 `async` 导出),该函数接收具有类似于 Astro 全局属性的上下文对象。它返回一个带有 `body` 的对象,Astro 将在构建时调用它并使用 `body` 中的内容来生成文件。 +端点导出一个 `GET` 函数(可选的以 `async` 导出),该函数接收具有类似于 Astro 全局属性的上下文对象。它返回一个带有 `body` 的对象,Astro 将在构建时调用它并使用 `body` 中的内容来生成文件。 ```js // 输出: /builtwith.json -export async function get({params, request}) { +export async function GET({params, request}) { return { body: JSON.stringify({ name: 'Astro', @@ -30,7 +30,7 @@ export async function get({params, request}) { 返回对象还可以具有 `encoding` 属性。它可以是任何可以被 Node.js 的 `fs.writeFile` 方法接收的 [`BufferEncoding`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/bdd02508ddb5eebcf701fdb8ffd6e84eabf47885/types/node/buffer.d.ts#L169)。例如,生成一个二进制png图像: ```ts title="src/pages/astro-logo.png.ts" {6} -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 { @@ -45,7 +45,7 @@ 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 }) => { ... ``` @@ -58,7 +58,7 @@ 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({ @@ -85,7 +85,7 @@ export function getStaticPaths () { ```ts title="src/pages/request-path.json.ts" import type { APIRoute } from 'astro'; -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { return { body: JSON.stringify({ path: new URL(request.url).pathname @@ -111,7 +111,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); @@ -136,7 +136,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,7 +147,7 @@ export async function get({ params, request }) { ### HTTP 方法 -除了 `get` 函数,您还可以使用任何 [HTTP 方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods) 作为名称导出函数。当有请求进来时,Astro 会检查该方法并调用相应的函数。 +除了 `GET` 函数,您还可以使用任何 [HTTP 方法](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Methods) 作为名称导出函数。当有请求进来时,Astro 会检查该方法并调用相应的函数。 你还可以导出 `all` 函数以匹配任何没有相应导出函数的方法。如果请求没有匹配的方法,它将重定向到您网站的 [404 页面](/zh-cn/core-concepts/astro-pages/#自定义-404-错误页面)。 @@ -158,7 +158,7 @@ export async function get({ params, request }) { ::: ```ts title="src/pages/methods.json.ts" -export const get: APIRoute = ({ params, request }) => { +export const GET: APIRoute = ({ params, request }) => { return { body: JSON.stringify({ message: "This was a GET!" @@ -166,7 +166,7 @@ export const get: APIRoute = ({ params, request }) => { } }; -export const post: APIRoute = ({ request }) => { +export const POST: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: "这是一个 POST 请求!" @@ -174,7 +174,7 @@ export const post: APIRoute = ({ request }) => { } } -export const del: APIRoute = ({ request }) => { +export const DELETE: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: "这是一个 DELETE 请求!" @@ -182,7 +182,7 @@ export const del: APIRoute = ({ request }) => { } } -export const all: APIRoute = ({ request }) => { +export const ALL: APIRoute = ({ request }) => { return { body: JSON.stringify({ message: `这是一个 ${request.method} 请求!` @@ -196,7 +196,7 @@ export const all: APIRoute = ({ 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 +217,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..0e19688ee8e80 100644 --- a/src/content/docs/zh-cn/guides/content-collections.mdx +++ b/src/content/docs/zh-cn/guides/content-collections.mdx @@ -706,7 +706,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..bf26997af5ec5 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,7 +146,7 @@ integrations: [ ```js title="astro.config.mjs" del={3,7} import { defineConfig } from 'astro/config' -import image from "@astrojs/image"; +import image from "@astrojs/react"; export default defineConfig({ integrations: [ 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 4eb1847a55719..62da9f4a080f0 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/netlify.mdx @@ -54,28 +54,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 @@ -84,10 +67,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - excludeMiddleware: true, - }, + adapter: netlify({ + edgeMiddleware: true, + }), }); ``` @@ -133,10 +115,9 @@ import netlify from '@astrojs/netlify/functions'; export default defineConfig({ output: 'server', - adapter: netlify(), - build: { - split: true, - }, + adapter: netlify({ + functionPerRoute: true, + }), }); ``` @@ -258,7 +239,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 fbcd75d0623e6..1138594938483 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/node.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/node.mdx @@ -159,7 +159,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/vercel.mdx b/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx index 24846b4563dfe..df291555d06ca 100644 --- a/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx +++ b/src/content/docs/zh-cn/guides/integrations-guide/vercel.mdx @@ -62,18 +62,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'; ``` @@ -96,7 +90,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 的跟踪脚本。 @@ -117,7 +111,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)以获取支持的参数的完整列表。 @@ -140,7 +134,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 服务。 @@ -181,7 +175,7 @@ import astroLogo from '../assets/logo.png'; ### includeFiles **类型:** `string[]`
-**适用于:** Edge, Serverless +**适用于:** Serverless 使用此属性来强制将文件与你的函数打包在一起。当你发现缺失文件时,这很有帮助。 @@ -198,10 +192,6 @@ export default defineConfig({ }); ``` -:::note -当为 Edge 构建时,所有依赖项都会被打包在一个文件中以节省空间。不会打包额外的文件。因此,如果你需要一些文件在函数内部,你必须在 includeFiles 中指定它们。 -::: - ### excludeFiles **类型:** `string[]`
@@ -233,10 +223,9 @@ import vercel from '@astrojs/vercel/serverless'; export default defineConfig({ output: 'server', - adapter: vercel(), - build: { - split: true, - }, + adapter: vercel({ + functionPerRoute: true, + }), }); ``` @@ -275,7 +264,7 @@ export default defineConfig({ `@astrojs/vercel/serverless` 适配器可以根据你代码库中的 Astro 中间件自动创建 Vercel Edge 中间件。 -这是一个选择性功能,需要将 `build.excludeMiddleware` 选项设置为 `true` : +这是一个选择性功能,需要将 `edgeMiddleware` 选项设置为 `true` : ```js // astro.config.mjs @@ -283,10 +272,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/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/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/install/auto.mdx b/src/content/docs/zh-cn/install/auto.mdx index 53671be779371..79c0f588af21d 100644 --- a/src/content/docs/zh-cn/install/auto.mdx +++ b/src/content/docs/zh-cn/install/auto.mdx @@ -12,7 +12,7 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' #### 前提准备 -- **Node.js** - `v16.12.0` 或更高版本。 +- **Node.js** - `v18.14.1` 或更高版本。 - **文本编辑器** - 我们建议使用安装有 [Astro 官方扩展](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode)的 [VS Code](https://code.visualstudio.com/)。 - **终端(Terminal)** - Astro 可以通过其命令行界面 (CLI) 访问。 diff --git a/src/content/docs/zh-cn/install/manual.mdx b/src/content/docs/zh-cn/install/manual.mdx index f87da10ce00eb..ebff6965aebeb 100644 --- a/src/content/docs/zh-cn/install/manual.mdx +++ b/src/content/docs/zh-cn/install/manual.mdx @@ -14,7 +14,7 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' #### 前提准备 -- **Node.js** - `v16.12.0` 或更高版本。 +- **Node.js** - `v18.14.1` 或更高版本。 - **文本编辑器** - 我们建议使用安装有 [Astro 官方扩展](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode)的 [VS Code](https://code.visualstudio.com/)。 - **终端(Terminal)** - Astro 可以通过其命令行界面 (CLI) 访问。 diff --git a/src/content/docs/zh-cn/recipes/build-forms-api.mdx b/src/content/docs/zh-cn/recipes/build-forms-api.mdx index a1b73e9fd13b2..ca4d432c9e85d 100644 --- a/src/content/docs/zh-cn/recipes/build-forms-api.mdx +++ b/src/content/docs/zh-cn/recipes/build-forms-api.mdx @@ -142,7 +142,7 @@ import PackageManagerTabs from "~/components/tabs/PackageManagerTabs.astro" ```ts title="src/pages/api/feedback.ts" "request.formData()" "post" import type { APIRoute } from "astro"; - export const post: APIRoute = async ({ request }) => { + export const POST: APIRoute = async ({ request }) => { const data = await request.formData(); const name = data.get("name"); const email = data.get("email"); diff --git a/src/content/docs/zh-cn/recipes/call-endpoints.mdx b/src/content/docs/zh-cn/recipes/call-endpoints.mdx index e41e5c24d411b..9308cfd9f1928 100644 --- a/src/content/docs/zh-cn/recipes/call-endpoints.mdx +++ b/src/content/docs/zh-cn/recipes/call-endpoints.mdx @@ -18,7 +18,7 @@ type: recipe ```ts title="src/pages/api/hello.ts" import type { APIRoute } from 'astro' - export const get: APIRoute = () => { + export const GET: APIRoute = () => { return new Response( JSON.stringify({ greeting: 'Hello', @@ -27,13 +27,13 @@ type: recipe } ``` -2. 在任何 Astro 页面上,从端点中导入 `get()` 方法。使用 [`Astro` 全局对象](/zh-cn/reference/api-reference/#astro-global) 来提供请求的上下文,并在页面使用响应数据。 +2. 在任何 Astro 页面上,从端点中导入 `GET()` 方法。使用 [`Astro` 全局对象](/zh-cn/reference/api-reference/#astro-global) 来提供请求的上下文,并在页面使用响应数据。 ```astro title="src/pages/index.astro" --- - import { get } from './api/hello.ts' + import { GET } from './api/hello.ts' - let response = await get(Astro) + let response = await GET(Astro) const data = await response.json() --- diff --git a/src/content/docs/zh-cn/recipes/captcha.mdx b/src/content/docs/zh-cn/recipes/captcha.mdx index cd01f2a144bad..a8e57db348ac1 100644 --- a/src/content/docs/zh-cn/recipes/captcha.mdx +++ b/src/content/docs/zh-cn/recipes/captcha.mdx @@ -14,10 +14,10 @@ type: recipe ## 操作步骤 -1. 创建一个 `post` 端点以接受 reCAPTCHA 数据,并使用 reCAPTCHA 的 API 对其进行验证。在这里,你可以安全地定义密钥值或读取环境变量。 +1. 创建一个 `POST` 端点以接受 reCAPTCHA 数据,并使用 reCAPTCHA 的 API 对其进行验证。在这里,你可以安全地定义密钥值或读取环境变量。 ```js title="src/pages/recaptcha.js" - export async function post({ request }) { + export async function POST({ request }) { const data = await request.json(); const recaptchaURL = 'https://www.google.com/recaptcha/api/siteverify'; diff --git a/src/content/docs/zh-cn/reference/api-reference.mdx b/src/content/docs/zh-cn/reference/api-reference.mdx index f29acd62cd4cc..33a5218505f9c 100644 --- a/src/content/docs/zh-cn/reference/api-reference.mdx +++ b/src/content/docs/zh-cn/reference/api-reference.mdx @@ -463,7 +463,7 @@ const orders = Array.from(Astro.locals.orders.entries()); ```ts title="endpoint.json.ts" import type { APIContext } from 'astro'; -export function get(context: APIContext) { +export function GET(context: APIContext) { // ... } ``` @@ -488,7 +488,7 @@ export function getStaticPaths() { ]; } -export function get({ params }: APIContext) { +export function GET({ params }: APIContext) { return { body: JSON.stringify({ id: params.id }) }; @@ -512,7 +512,7 @@ export function getStaticPaths() { ]; } -export function get({ props }: APIContext) { +export function GET({ props }: APIContext) { return { body: JSON.stringify({ author: props.author }), }; @@ -528,7 +528,7 @@ export function get({ props }: APIContext) { ```ts import type { APIContext } from 'astro'; -export function get({ request }: APIContext) { +export function GET({ request }: APIContext) { return { body: `Hello ${request.url}` } @@ -556,7 +556,7 @@ export function get({ request }: APIContext) { ```ts import type { APIContext } from 'astro'; -export function get({ clientAddress }: APIContext) { +export function GET({ clientAddress }: APIContext) { return { body: `Your IP address is: ${clientAddress}` } @@ -580,7 +580,7 @@ export function get({ clientAddress }: APIContext) { ```ts title="src/pages/site-info.json.ts" import type { APIContext } from 'astro'; -export function get({ generator, site }: APIContext) { +export function GET({ generator, site }: APIContext) { const body = JSON.stringify({ generator, site }); return new Response(body); } @@ -595,7 +595,7 @@ export function get({ generator, site }: APIContext) { ```ts import type { APIContext } from 'astro'; -export function get({ redirect }: APIContext) { +export function GET({ redirect }: APIContext) { return redirect('/login', 302); } ``` @@ -1052,17 +1052,13 @@ export default function () { ## 内置组件 -Astro 包括几个内置的组件供你在你的项目中使用。在 `.astro` 文件中可以通过 `import {} from 'astro/components';` 引用所有的内置组件。 - -### `<Markdown />` - -Markdown 组件不再内置到 Astro 中。请在 Markdown 页面查看如何[将 Markdown 导入 Astro 文件](/zh-cn/guides/markdown-content/#导入-markdown)。 +Astro 包括几个内置的组件供你在你的项目中使用。在 `.astro` 文件中可以通过 `import {} from 'astro:components';` 引用所有的内置组件。 ### `<Code />` ```astro 'theme="dark-plus"' /wrap\b/ /(inline) \/>/ --- -import { Code } from 'astro/components'; +import { Code } from 'astro:components'; --- <!-- 使用语法凸显部分 JavaScript 代码--> <Code code={`const foo = 'bar';`} lang="js" /> @@ -1126,7 +1122,7 @@ import { Prism } from '@astrojs/prism'; ```astro --- -import { Debug } from 'astro/components'; +import { Debug } from 'astro:components'; const serverObject = { a: 0, b: "string", diff --git a/src/content/docs/zh-cn/reference/error-reference.mdx b/src/content/docs/zh-cn/reference/error-reference.mdx index f3edf01ed9c14..512bf49a33b95 100644 --- a/src/content/docs/zh-cn/reference/error-reference.mdx +++ b/src/content/docs/zh-cn/reference/error-reference.mdx @@ -48,6 +48,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ - [**AstroGlobNoMatch**](/zh-cn/reference/errors/astro-glob-no-match/)<br/>Astro.glob() did not match any files. - [**RedirectWithNoLocation**](/zh-cn/reference/errors/redirect-with-no-location/)<br/>A redirect must be given a location with the `Location` header. - [**InvalidDynamicRoute**](/zh-cn/reference/errors/invalid-dynamic-route/)<br/>Invalid dynamic route. +- [**MissingSharp**](/zh-cn/reference/errors/missing-sharp/)<br/>Could not find Sharp. - [**UnknownViteError**](/zh-cn/reference/errors/unknown-vite-error/)<br/>Unknown Vite Error. - [**FailedToLoadModuleSSR**](/zh-cn/reference/errors/failed-to-load-module-ssr/)<br/>Could not import file. - [**InvalidGlob**](/zh-cn/reference/errors/invalid-glob/)<br/>Invalid glob pattern. diff --git a/src/content/docs/zh-cn/reference/errors/locals-not-an-object.mdx b/src/content/docs/zh-cn/reference/errors/locals-not-an-object.mdx index d634310b4fcac..3dcf30c68628e 100644 --- a/src/content/docs/zh-cn/reference/errors/locals-not-an-object.mdx +++ b/src/content/docs/zh-cn/reference/errors/locals-not-an-object.mdx @@ -13,7 +13,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ 例如: ```ts -import { defineMiddleware } from "astro/middleware"; +import { defineMiddleware } from "astro:middleware"; export const onRequest = defineMiddleware((context, next) => { context.locals = 1541; return next(); diff --git a/src/content/docs/zh-cn/reference/errors/middleware-no-data-or-next-called.mdx b/src/content/docs/zh-cn/reference/errors/middleware-no-data-or-next-called.mdx index 51b65a32a1721..c514ad2b3589f 100644 --- a/src/content/docs/zh-cn/reference/errors/middleware-no-data-or-next-called.mdx +++ b/src/content/docs/zh-cn/reference/errors/middleware-no-data-or-next-called.mdx @@ -13,7 +13,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ 例如: ```ts -import { defineMiddleware } from "astro/middleware"; +import { defineMiddleware } from "astro:middleware"; export const onRequest = defineMiddleware((context, _) => { // 没有返回任何数据或者调用 `next` context.locals.someData = false; diff --git a/src/content/docs/zh-cn/reference/errors/middleware-not-aresponse.mdx b/src/content/docs/zh-cn/reference/errors/middleware-not-aresponse.mdx index c15fa8de1863d..b70721833176f 100644 --- a/src/content/docs/zh-cn/reference/errors/middleware-not-aresponse.mdx +++ b/src/content/docs/zh-cn/reference/errors/middleware-not-aresponse.mdx @@ -13,7 +13,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ 例如: ```ts -import { defineMiddleware } from "astro/middleware"; +import { defineMiddleware } from "astro:middleware"; export const onRequest = defineMiddleware(() => { return "string" }); diff --git a/src/content/docs/zh-cn/reference/errors/static-redirect-not-available.mdx b/src/content/docs/zh-cn/reference/errors/static-redirect-not-available.mdx index 929938ec0fb6a..66c225df0052a 100644 --- a/src/content/docs/zh-cn/reference/errors/static-redirect-not-available.mdx +++ b/src/content/docs/zh-cn/reference/errors/static-redirect-not-available.mdx @@ -5,7 +5,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ --- :::caution[已废弃] -从 2.6 版本开始已弃用 +从 2.6 版本开始已弃用。 ::: > **StaticRedirectNotAvailable**: 重定向仅在设置为 `output: 'server'` 或 `output: 'hybrid'` 时可用. 如果需要使用 SSR 的功能,请更新 Astro 配置。 diff --git a/src/content/docs/zh-cn/reference/errors/unsupported-image-format.mdx b/src/content/docs/zh-cn/reference/errors/unsupported-image-format.mdx index e9de2bd98fcf7..aea8683a95ed4 100644 --- a/src/content/docs/zh-cn/reference/errors/unsupported-image-format.mdx +++ b/src/content/docs/zh-cn/reference/errors/unsupported-image-format.mdx @@ -10,11 +10,11 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ 内置的图像服务当前并不支持优化所有图像格式。 -对于不支持的格式,如 SVG 和 GIF,你可以直接使用 `img` 标签: +对于不支持的格式,如 GIF,你可以直接使用 `img` 标签: ```astro --- -import rocket from '../assets/images/rocket.svg'; +import rocket from '../assets/images/rocket.gif'; --- <img src={rocket.src} width={rocket.width} height={rocket.height} alt="A rocketship in space." /> diff --git a/src/content/docs/zh-cn/reference/image-service-reference.mdx b/src/content/docs/zh-cn/reference/image-service-reference.mdx index 5286de3eac592..08f7177b3deac 100644 --- a/src/content/docs/zh-cn/reference/image-service-reference.mdx +++ b/src/content/docs/zh-cn/reference/image-service-reference.mdx @@ -137,7 +137,7 @@ export default service; import type { APIRoute } from "astro"; import { getConfiguredImageService, imageConfig } from 'astro:assets'; -export const get: APIRoute = async ({ request }) => { +export const GET: APIRoute = async ({ request }) => { const imageService = await getConfiguredImageService(); const imageTransform = imageService.parseURL(new URL(request.url), imageConfig); diff --git a/src/content/docs/zh-cn/tutorial/1-setup/1.mdx b/src/content/docs/zh-cn/tutorial/1-setup/1.mdx index e85ceb36627e4..35dc0dbc9c602 100644 --- a/src/content/docs/zh-cn/tutorial/1-setup/1.mdx +++ b/src/content/docs/zh-cn/tutorial/1-setup/1.mdx @@ -26,7 +26,7 @@ import PreCheck from '~/components/tutorial/PreCheck.astro'; ### Node.js -要在你的系统上运行 Astro,你还需要安装 [**Node.js**](https://nodejs.org/),并且版本为 `v16.12.0` 或更高版本。 +要在你的系统上运行 Astro,你还需要安装 [**Node.js**](https://nodejs.org/),并且版本为 `v18.14.1` 或更高版本。 要检查是否已安装兼容版本,请在终端中运行以下命令: @@ -34,12 +34,12 @@ import PreCheck from '~/components/tutorial/PreCheck.astro'; node -v // 输出示例 -v16.14.0 +v18.14.1 ``` -如果该命令返回的版本号高于 `v16.12.0`,那么你就可以继续了! +如果该命令返回的版本号高于 `v18.14.1`,那么你就可以继续了! -如果命令返回错误消息,如 `Command 'node' not found`,或者版本号低于 `v16.12.0`,那么你需要[安装兼容的 Node.js 版本](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。 +如果命令返回错误消息,如 `Command 'node' not found`,或者版本号低于 `v18.14.1`,那么你需要[安装兼容的 Node.js 版本](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。 ### 代码编辑器 diff --git a/src/content/docs/zh-cn/tutorial/5-astro-api/4.mdx b/src/content/docs/zh-cn/tutorial/5-astro-api/4.mdx index 99479b751fc3e..ca15465943210 100644 --- a/src/content/docs/zh-cn/tutorial/5-astro-api/4.mdx +++ b/src/content/docs/zh-cn/tutorial/5-astro-api/4.mdx @@ -73,7 +73,7 @@ Astro 提供了一个可自定义包,用于快速为你的网站添加一个 R import rss, { pagesGlobToRssItems } from '@astrojs/rss'; - export async function get() { + export async function GET() { return rss({ title: 'Astro Learner | Blog', description: 'My journey learning Astro', From 64184b4d1173bbfbb332d436c98d0f98f5ac7831 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 09:02:54 +0800 Subject: [PATCH 02/57] Update why-astro.mdx --- src/content/docs/zh-cn/concepts/why-astro.mdx | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/src/content/docs/zh-cn/concepts/why-astro.mdx b/src/content/docs/zh-cn/concepts/why-astro.mdx index c89ac94a126eb..8d6735de14317 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是... 1. [ **以内容为中心** ](#以内容为中心):Astro 专为内容丰富的网站而设计。 2. [ **服务器优先** ](#服务器优先):网站在服务器上渲染 HTML 时运行速度更快。 3. [ **默认快速** ](#默认快速):在 Astro 中构建缓慢的网站是不可能的。 -4. [ **易于使用** ](#易于使用):您不需要成为专家即可使用 Astro 构建某些内容。 +4. [ **易于使用** ](#易于使用):你不需要成为专家即可使用 Astro 构建某些内容。 5. [ **功能齐全且灵活** ](#功能齐全且灵活):超100多种 Astro 集成可供选择。 ## 以内容为中心 @@ -23,16 +23,16 @@ 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/) 等关键指标——这对于以内容为中心的网站没有多大意义,因为这些网站的首次加载性能至关重要。 @@ -42,7 +42,7 @@ 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/)) @@ -59,23 +59,23 @@ Astro 的魔力在于它如何将上述两个值(内容焦点于服务器优 ## 易于使用 -**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 的设计比其他UI框架和语言更简单,其中一个重要原因是 Astro 被设计为在服务器上渲染而不是浏览器,这意味着你无需担心:React Hooks、stale closures(React)、refs(Vue)、observables(Svelte)、atoms、selectors、reactions or derivations。服务器上没有响应式,因此这些复杂性都消失了。 -我们最喜欢的谚语之一是:**选择加入复杂性。** 我们设计 Astro 是为了尽可能多地从开发人员体验中消除“所需的复杂性”,尤其是您首次加入时。您可以在 Astro中使用 HTML和CSS构建“Hello World”示例网站。然后当您需要构建更强大的功能时,您可以随时获得新功能和API。 +我们最喜欢的谚语之一是:**选择加入复杂性。** 我们设计 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 中得到官方支持。你甚至可以在同一页面上混合和匹配不同的框架,使未来的迁移更容易,并防止项目锁定到单个框架。 From afe503bf20a6a16c1689b0c026e1a01afd3e2499 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 09:13:19 +0800 Subject: [PATCH 03/57] Update content-collection.mdx --- src/content/docs/zh-cn/guides/content-collections.mdx | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/content/docs/zh-cn/guides/content-collections.mdx b/src/content/docs/zh-cn/guides/content-collections.mdx index 0e19688ee8e80..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 From 8ff47b672dc2490bea11b62f87d2cba64d7f9eda Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 09:26:20 +0800 Subject: [PATCH 04/57] Update cloudflare.mdx --- .../guides/integrations-guide/cloudflare.mdx | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) 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 0d2dc3fcc2a23..29131865a1045 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` From 0e67ca34d141f15e0a843943713db4675b6584f4 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 09:34:24 +0800 Subject: [PATCH 05/57] Update markdown-content.mdx --- .../docs/zh-cn/guides/markdown-content.mdx | 57 +------------------ 1 file changed, 1 insertion(+), 56 deletions(-) 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 语法。 From affd6ce0d5343ea45e5be6c84f00d53d31d59b19 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 09:47:15 +0800 Subject: [PATCH 06/57] Update styling.mdx --- src/content/docs/zh-cn/guides/styling.mdx | 30 ++++++++++++++++------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/src/content/docs/zh-cn/guides/styling.mdx b/src/content/docs/zh-cn/guides/styling.mdx index 587c1932265f2..2ec0f5f6f721f 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,7 @@ import MyComponent from "../components/MyComponent.astro" <MyComponent class="red">这将是红色!</MyComponent> ``` -这种模式可以让你直接给子组件添加样式。Astro 会自动将父组件的作用域类名(例如 `astro-HHNQFKH6`)通过 `class` 属性传递给子组件,使得子组件也在父组件的作用域中。 +这种模式可以让你直接给子组件添加样式。Astro 会自动将父组件的作用域类名(例如 `astro-hhnqfkh6`)通过 `class` 属性传递给子组件,使得子组件也在父组件的作用域中。 :::note[父组件的作用域类名] 由于 `class` 属性包含了子组件在父组件的作用域中,因此父组件的样式可以传递到子组件中。为了避免这种情况,确保在子组件中使用唯一的类名。 @@ -525,24 +525,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: 'nerver' } }); ``` -`'auto'` 选项只会将小于 `vite.build.assetsInlineLimit` 阈值的样式表内联,以减少对较小样式表的请求次数。。而较大的样式表,比如被所有页面用到的全局样式表,仍然会从外部获取并缓存。该选项可在加载的样式表数量和在页面中缓存的样式之间取得平衡。 - 你也可以将该选项设置为 `'always'` ,这样就可以内联所有的样式表了。 ## 高级 From 4776595fa67b883a14acb570024721ff280f11fa Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 10:04:52 +0800 Subject: [PATCH 07/57] Update preact.mdx --- .../guides/integrations-guide/preact.mdx | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) 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..472cda427cd66 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 框架特定的转换。如果你只向你的项目中添加了一个 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 组件。 From 3a3933e6315a9cbd66d611ed11aa9c7599fd21df Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 10:07:27 +0800 Subject: [PATCH 08/57] Update react.mdx & solid-js.mdx --- .../zh-cn/guides/integrations-guide/react.mdx | 33 +++++++++++++++++ .../guides/integrations-guide/solid-js.mdx | 35 +++++++++++++++++++ 2 files changed, 68 insertions(+) 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..2a5a4445997a2 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 框架特定的转换。如果你只向你的项目中添加了一个 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..bedaa8f32400f 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 框架特定的转换。如果你只向你的项目中添加了一个 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` 频道。 我们友好的支持小队成员随时为你提供帮助! From 5611cec181e5cc7de8a9e7ed542dbedec2eb0c66 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 10:49:58 +0800 Subject: [PATCH 09/57] Update cli-reference.mdx --- .../docs/zh-cn/reference/cli-reference.mdx | 145 ++++++++++++++++-- 1 file changed, 134 insertions(+), 11 deletions(-) diff --git a/src/content/docs/zh-cn/reference/cli-reference.mdx b/src/content/docs/zh-cn/reference/cli-reference.mdx index 99e1f8c0aa388..2b974dc46d2fd 100644 --- a/src/content/docs/zh-cn/reference/cli-reference.mdx +++ b/src/content/docs/zh-cn/reference/cli-reference.mdx @@ -101,7 +101,7 @@ Global Flags } ``` -你经常会使用这些 `astro` 命令,或者运行它们的脚本,而不带任何标志。 当你想要自定义命令的行为时,可以向命令添加标志。 例如,你可能希望在不同的端口上启动开发服务器,或者构建包含草稿页面的网站。 +你经常会使用这些 `astro` 命令,或者运行它们的脚本,而不带任何标志。 当你想要自定义命令的行为时,可以向命令添加标志。 例如,你可能希望在不同的端口上启动开发服务器,或者使用详细日志构建站点以进行调试。 <PackageManagerTabs> <Fragment slot="npm"> @@ -109,8 +109,8 @@ Global Flags # 使用 `package.json` 中的 `start` 脚本,以端口 8080 启动开发服务器 npm run start -- --port 8080 - # 使用 `package.json` 中的 `build` 脚本,构建包含草稿页面的网站 - npm run build -- --drafts + # 使用 `package.json` 中的 `build` 脚本,构建带有详细日志的网站 + npm run build -- --verbose ``` (额外的`--` 在 `--port` 标志之前是必须的,因为 `npm` 需要将你的标志传递给 `astro` 命令。) </Fragment> @@ -119,8 +119,8 @@ Global Flags # 使用 `package.json` 中的 `start` 脚本,以端口 8080 启动开发服务器 pnpm start --port 8080 - # 使用 `package.json` 中的 `build` 脚本,构建包含草稿页面的网站 - pnpm build --drafts + # 使用 `package.json` 中的 `build` 脚本,构建带有详细日志的网站 + pnpm build --verbose ``` </Fragment> <Fragment slot="yarn"> @@ -128,8 +128,8 @@ Global Flags # 使用 `package.json` 中的 `start` 脚本,以端口 8080 启动开发服务器 yarn start --port 8080 - # 使用 `package.json` 中的 `build` 脚本,构建包含草稿页面的网站 - yarn build --drafts + # 使用 `package.json` 中的 `build` 脚本,构建带有详细日志的网站 + yarn build --verbose ``` </Fragment> </PackageManagerTabs> @@ -164,10 +164,6 @@ Global Flags 使用这些标志来自定义构建。 对于与其他 Astro 命令共享的标志,请参阅下面的[通用标志](#通用标志)。 -#### `--drafts` - -在构建中包含 [Markdown 草稿页面](/zh-cn/guides/markdown-content/#草稿页面)。 - ## `astro preview` 启动本地静态文件服务器,为静态的 `dist/` 目录提供服务。 @@ -316,3 +312,130 @@ astro --config config/astro.config.mjs dev ### `--help` 打印帮助信息并退出。 + + +## 高级 API(实验性) + +如果你需要在运行 Astro 时获得更多的控制权,`"astro"` 包也导出了 API 来以编程方式运行 CLI 命令。 + +这些 API 是实验性的,它们的 API 签名可能会改变。任何更新都将在 [Astro 更新日志](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) 中提到,下面的信息将始终显示当前的、最新的信息。 + +### `AstroInlineConfig` + +`AstroInlineConfig` 类型由下面所有的命令 API 使用。它继承了用户的 [Astro 配置](/zh-cn/reference/configuration-reference/) 类型: + +```ts +interface AstroInlineConfig extends AstroUserConfig { + configFile?: string | false; + mode?: "development" | "production"; + logLevel?: "debug" | "info" | "warn" | "error" | "silent"; +} +``` + +#### `configFile` + +<p> + +**类型:** `string | false`<br /> +**默认值:** `undefined` +</p> + +一个自定义的 Astro 配置文件路径。 + +如果这个值是 undefined 的(默认)或未设置的,Astro 将在 `root` 目录下搜索 `astro.config.(js,mjs,ts)` 文件,并在找到时加载配置文件。 + +如果设置了相对路径,它将基于当前工作目录解析。 + +设置为 `false` 以禁用加载任何配置文件。 + +当与加载的用户配置合并时,传递给此对象的内联配置将具有最高优先级。 + +#### `mode` + +<p> + +**类型:** `"development" | "production"`<br /> +**默认值:** 当运行 `astro dev` 时为 `"development"` , 当运行 `astro build` 时为 `"production"` +</p> + +构建你的网站以生成 “development” 或 “production” 代码时使用的模式。 + +#### `logLevel` + +<p> + +**类型:** `"debug" | "info" | "warn" | "error" | "silent"`<br /> +**默认值:** `"info"` +</p> + +Astro 记录的消息的日志级别。 + +- `"debug"`: 记录所有内容,包括干扰调试诊断。 +- `"info"`: 记录信息类型的消息,警告,和错误等日志。 +- `"warn"`: 记录警告和错误日志。 +- `"error"`: 只记录错误日志。 +- `"silent"`: 不开启日志。 + +### `dev()` + +**类型:** `(inlineConfig: AstroInlineConfig) => AstroDevServer` + +和 [`astro dev`](#astro-dev) 类似,使用它来运行 Astro 的开发服务器。 + +```js +import { dev } from "astro"; + +const devServer = await dev({ + root: "./my-project", +}); + +// 在需要时停止服务器 +await devServer.stop(); +``` + +### `build()` + +**类型:** `(inlineConfig: AstroInlineConfig) => void` + +和 [`astro build`](#astro-build) 类似,使用它来构建你的网站以进行部署。 + +```js +import { build } from "astro"; + +await build({ + root: "./my-project", +}); +``` + +### `preview()` + +**类型:** `(inlineConfig: AstroInlineConfig) => AstroPreviewServer` + +和 [`astro preview`](#astro-preview) 类似,它启动一个本地服务器为静态的 `dist/` 目录提供预览服务。 + +```js +import { preview } from "astro"; + +const previewServer = await preview({ + root: "./my-project", +}); + +// 在需要时停止服务器 +await previewServer.stop(); +``` + +### `sync()` + +**类型:** `(inlineConfig: AstroInlineConfig) => number` + +和 [`astro sync`](#astro-sync) 类似,它为所有 Astro 模块生成 TypeScript 类型。 + +```js +import { sync } from "astro"; + +const exitCode = await sync({ + root: "./my-project", +}); + +process.exit(exitCode) +``` From a033711580547173a4127f314074097c17e3f044 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 15:37:16 +0800 Subject: [PATCH 10/57] Update adapter & configuration reference --- .../zh-cn/reference/adapter-reference.mdx | 235 +++++++++++++++++- .../reference/configuration-reference.mdx | 87 ++----- 2 files changed, 252 insertions(+), 70 deletions(-) diff --git a/src/content/docs/zh-cn/reference/adapter-reference.mdx b/src/content/docs/zh-cn/reference/adapter-reference.mdx index a8ac2cef0c98d..e23e3e746ffc8 100644 --- a/src/content/docs/zh-cn/reference/adapter-reference.mdx +++ b/src/content/docs/zh-cn/reference/adapter-reference.mdx @@ -2,6 +2,8 @@ title: Astro 适配器 API --- +import Since from '~/components/Since.astro'; + Astro 可以轻松部署到任何云托管平台,以实现服务端渲染(SSR)。该能力由**适配器**[集成](/zh-cn/reference/integrations-reference/)提供,请参阅 [SSR 指南](/zh-cn/guides/server-side-rendering/#添加一个适配器) 了解如何使用现有的适配器。 ## 什么是适配器 @@ -25,7 +27,10 @@ export default function createIntegration() { 'astro:config:done': ({ setAdapter }) => { setAdapter({ name: '@matthewp/my-adapter', - serverEntrypoint: '@matthewp/my-adapter/server.js' + serverEntrypoint: '@matthewp/my-adapter/server.js', + supportedAstroFeatures: { + staticOutput: 'stable' + } }); }, }, @@ -37,10 +42,57 @@ export default function createIntegration() { ```ts interface AstroAdapter { - name: string; - serverEntrypoint?: string; - exports?: string[]; + name: string; + serverEntrypoint?: string; + exports?: string[]; + adapterFeatures: AstroAdapterFeatures; + supportedAstroFeatures: AstroFeatureMap; +} + +export interface AstroAdapterFeatures { + /** + * 创建一个与 Astro 中间件通信的边缘函数 + */ + edgeMiddleware: boolean; + /** + * 仅 SSR 可用。每个路由都会成为自己的函数/文件 + */ + functionPerRoute: boolean; } + +export type SupportsKind = 'unsupported' | 'stable' | 'experimental' | 'deprecated'; + +export type AstroFeatureMap = { + /** + * 该适配器是否能够为静态页面提供服务 + */ + staticOutput?: SupportsKind; + /** + * 该适配器是否能够为静态页面或通过服务器渲染的页面提供服务。 + */ + hybridOutput?: SupportsKind; + /** + * 此适配器是否能够为 SSR 页面提供服务 + */ + serverOutput?: SupportsKind; + /** + * 此适配器对 assets 的支持程度 + */ + assets?: AstroAssetsFeature; +}; + +export interface AstroAssetsFeature { + supportKind?: SupportsKind; + /** + * 此适配器是否在与库 `sharp` 兼容的环境中部署文件 + */ + isSharpCompatible?: boolean; + /** + * 此适配器是否在与库 `squoosh` 兼容的环境中部署文件 + */ + isSquooshCompatible?: boolean; +} + ``` 这些属性分别是: @@ -48,6 +100,8 @@ interface AstroAdapter { * __name__:适配器的唯一名称,用于日志记录。 * __serverEntrypoint__:服务端渲染的入口。 * __exports__:导出数组,与 `createExports` 配套使用(在下文中说明)。 +* __adapterFeatures__:一个对象,用于启用适配器必须支持的特定功能。这些功能将改变构建输出,适配器必须实现适当的逻辑来处理不同的输出。 +* __supportedAstroFeatures__:Astro 内置功能的映射。这允许 Astro 确定适配器无法或不愿意支持的功能,以便提供适当的错误消息。 ### 服务端入口 @@ -187,3 +241,176 @@ if(app.match(request)) { ``` 当[将适配器发布到 npm](https://docs.npmjs.com/cli/v8/commands/npm-publish) 后,执行 `astro add example` 命令,即可安装适配器以及在 `package.json` 文件中指定的对等依赖。我们将指导用户手动更新他们的项目配置。 + + + +## Astro features + +<Since v="3.0.0" /> + +Astro features 是适配器告诉 Astro 它们是否能够支持某个特性的一种方式,也是适配器支持程度的一种方式。 + +当使用这些属性时,Astro 将: +- 运行特定的验证; +- 抛出(emit)上下文日志; + +这些操作是基于支持或不支持的特性、支持程度以及用户使用的配置来运行的。 + +以下配置告诉 Astro,该适配器对 assets 有实验性支持,但该适配器与内置服务 Sharp 和 Squoosh 不兼容: + +```js title="my-adapter.mjs" ins={9-15} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + supportedAstroFeatures: { + assets: { + supportKind: "experimental", + isSharpCompatible: false, + isSquooshCompatible: false + } + } + }); + }, + }, + }; +} +``` + +Astro 将在终端中记录**警告**: + +``` +/* 该功能是实验性的,可能会出现问题或更改。*/ +[@matthewp/my-adapter] The feature is experimental and subject to issues or changes. +``` + +或者,如果用于 assets 的服务与适配器不兼容,则会抛出错误: + +``` +/* 当前选择的适配器 `@matthewp/my-adapter` 与 "Sharp" 服务不兼容。你的项目将无法构建。*/ +[@matthewp/my-adapter] The currently selected adapter `@matthewp/my-adapter` is not compatible with the service "Sharp". Your project will NOT be able to build. +``` + +## Adapter features + +一组可以改变产出文件输出的特性。当适配器选择这些特性时,它们将在特定的钩子中获得额外的信息。 + +### `functionPerRoute` + +这是一个仅在使用 SSR 时启用的功能。默认情况下,Astro 会产出一个 `entry.mjs` 文件,该文件负责在每个请求上产出渲染的页面。 + +当 `functionPerRoute` 为 `true` 时,Astro 会为项目中定义的每个路由创建一个单独的文件。 +每个文件都只会渲染一个页面。页面将在 `dist/pages/` 目录中产出,产出的文件将保持 `src/pages/` 目录的相同文件路径。 + +通过将 `true` 传递给适配器来启用此功能。 + +```js title="my-adapter.mjs" ins={9-11} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + functionPerRoute: true + } + }); + }, + }, + }; +} +``` + +然后,使用 [`astro:build:ssr`](/zh-cn/reference/integrations-reference/#astrobuildssr) 钩子,它将为你提供一个 `entryPoints` 对象,该对象将页面路由映射到构建后的物理文件。 + +```js title="my-adapter.mjs" ins={15-19} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + functionPerRoute: true + } + }); + }, + + 'astro:build:ssr': ({ entryPoints }) => { + for (const [route, entryFile] of entryPoints) { + // 对路由和条目文档执行某些操作 + } + } + }, + }; +} +``` + +:::caution +`entryFile` 是 `URL` 类型,表示文件系统中文件的物理路径。这意味着路径会根据代码运行的操作系统而改变。 +::: + +### `edgeMiddleware` + +定义在构建时是否会打包任何 SSR 中间件代码。 + +启用此功能时,会阻止在构建期间将中间件代码打包并导入到所有页面中: + +```js title="my-adapter.mjs" ins={9-11} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + edgeMiddleware: true + } + }); + }, + }, + }; +} +``` + +然后,使用 [`astro:build:ssr`](/zh-cn/reference/integrations-reference/#astrobuildssr) 钩子,它将为你提供一个 `middlewareEntryPoint`,一个指向文件系统上物理文件的 `URL`。 + +```js title="my-adapter.mjs" ins={15-19} +export default function createIntegration() { + return { + name: '@matthewp/my-adapter', + hooks: { + 'astro:config:done': ({ setAdapter }) => { + setAdapter({ + name: '@matthewp/my-adapter', + serverEntrypoint: '@matthewp/my-adapter/server.js', + adapterFeatures: { + edgeMiddleware: true + } + }); + }, + + 'astro:build:ssr': ({ middlewareEntryPoint }) => { + // 请记住检查此属性是否退出,如果适配器未选择加入该功能,则它将是 `undefined` + if (middlewareEntryPoint) { + createEdgeMiddleware(middlewareEntryPoint) + } + } + }, + }; +} + +function createEdgeMiddleware(middlewareEntryPoint) { + // 通过你的打包工具生成一个新的物理文件 +} +``` diff --git a/src/content/docs/zh-cn/reference/configuration-reference.mdx b/src/content/docs/zh-cn/reference/configuration-reference.mdx index c3cd186ac4b73..fe16f7c747ced 100644 --- a/src/content/docs/zh-cn/reference/configuration-reference.mdx +++ b/src/content/docs/zh-cn/reference/configuration-reference.mdx @@ -183,16 +183,16 @@ $ astro build --root ./my-project-directory <p> **类型:** `boolean`<br /> -**默认值:** `false` +**默认值:** `true` </p> -这是一个用于缩小 HTML 输出并减少 HTML 文件大小的选项。当启用时,Astro 会从 `.astro` 组件中移除所有空格,包括换行符。这个优化会在开发模式和最终构建中生效。 +这是一个用于缩小 HTML 输出并减少 HTML 文件大小的选项。默认情况下,Astro 会从 `.astro` 组件中移除所有空格,包括换行符。这个优化会在开发模式和最终构建中生效。 -要启用这个优化,将 `compressHTML` 标志设置为 `true`。 +要禁用 HTML 压缩,请将 `compressHTML` 标志设置为 `false`。 ```js { - compressHTML: true + compressHTML: false } ``` @@ -213,12 +213,7 @@ $ astro build --root ./my-project-directory 当使用这个选项时,你所有的静态资源导入和 URL 都需要添加 base 作为前缀。你可以通过 `import.meta.env.BASE_URL` 访问这个值。 -默认情况下,`import.meta.env.BASE_URL` 的值包含一个尾部斜杠。如果你将 [`trailingSlash`](/zh-cn/reference/configuration-reference/#trailingslash) 选项设置为 `'never'`,则在静态资源的导入和 URL 中需要手动添加它。 - -```astro -<a href="/docs/about/">About</a> -<img src=`${import.meta.env.BASE_URL}/image.png`> -``` +`import.meta.env.BASE_URL` 的值会遵从你的 `trailingSlash` 配置,如果你明确地包含一个尾部斜杠,或者设置了 `trailingSlash: "always"`,它将包含一个尾部斜杠。如果设置了 `trailingSlash: "never"`,`BASE_URL` 将不包含尾部斜杠,即使 `base` 中包含。 ### trailingSlash @@ -253,19 +248,21 @@ $ astro build --root ./my-project-directory <p> -**类型:** `'where' | 'class'`<br /> -**默认值:** `'where'`<br /> +**类型:** `'where' | 'class'` | 'attribute'`<br /> +**默认值:** `'attribute'`<br /> <Since v="2.4" /> </p> 指定 Astro 组件内部样式作用范围。可选项包括: - `'where'` - 使用 `:where` 选择器,不会增加特异性。 - `'class'` - 使用基于类的选择器,会增加 +1 的特异性。 + - `'attribute'` - 使用 `data-` 属性,不会增加特异性。 使用 `'class'` 可以确保 Astro 组件内的元素选择器覆盖全局样式默认值(例如来自全局样式表)。 使用 `'where'` 可以更好地控制特异性,但需要使用更高特异性的选择器、层级和其他工具来控制应用的选择器。 +使用 `'attribute'` 在你操作元素的 `class` 属性时很有用,这样你就可以避免你自己的样式逻辑和 Astro 的样式应用之间的冲突。 ### adapter @@ -492,7 +489,7 @@ export default defineConfig({ <p> **类型:** `'always' | 'auto' | 'never'`<br /> -**默认值:** `never`<br /> +**默认值:** `auto`<br /> <Since v="2.6.0" /> </p> @@ -505,7 +502,7 @@ export default defineConfig({ ```js { build: { - inlineStylesheets: `auto`, + inlineStylesheets: `never`, }, } ``` @@ -516,45 +513,24 @@ export default defineConfig({ <p> **类型:** `boolean`<br /> -**默认值:** `false`<br /> -<Since v="2.7.0" /> +**默认值:** `false` </p> -决定 SSR 代码在构建时应如何进行打包。 - -当 `split` 设置为 `true` 时,Astro 将为每个页面生成一个文件。每个生成的文件将只渲染一个页面。 - -生成的文件将位于 `dist/pages/` 目录下,并且生成的文件路径将与 `src/pages` 目录下的文件路径保持一致。 - -```js -{ - build: { - split: true - } -} -``` +构建配置项 `build.split` 已被适配器配置项 [`functionPerRoute`](/zh-cn/reference/adapter-reference/#functionperroute) 替换。 +请查看你的 [SSR 适配器文档](/zh-cn/guides/integrations-guide/#官方集成) 以了解如何使用 `functionPerRoute` 来定义你的 SSR 代码如何打包。 ### build.excludeMiddleware <p> **类型:** `boolean`<br /> -**默认值:** `false`<br /> -<Since v="2.8.0" /> +**默认值:** `false` </p> -决定在构建时是否对任何 SSR 中间件代码进行打包。 - -当启用时,中间件代码不会在构建期间被打包和被导入到所有页面。如果要手动执行和导入中间件代码,请设置 `build.excludeMiddleware: true`: +构建配置项 `build.excludeMiddleware` 已被适配器配置项 [`edgeMiddleware`](/zh-cn/reference/adapter-reference/#edgemiddleware) 替换。 -```js -{ - build: { - excludeMiddleware: true - } -} -``` +请查看你的 [SSR 适配器文档](/zh-cn/guides/integrations-guide/#官方集成) 以了解如何使用 `functionPerRoute` 来定义你的 SSR 代码如何打包。 ## 服务器选项 @@ -572,7 +548,7 @@ export default defineConfig({ ```js { // 示例:使用函数语法,根据命令进行定制 - server: ({ command }) => ({ port: command === 'dev' ? 3000 : 4000 }) + server: ({ command }) => ({ port: command === 'dev' ? 4321 : 4000 }) } ``` @@ -596,7 +572,7 @@ export default defineConfig({ <p> **类型**:`number`<br /> -**默认值**:`3000` +**默认值**:`4321` </p> 设置服务器监听端口。 @@ -627,7 +603,7 @@ export default defineConfig({ <p> **类型:**`Object`<br /> -**默认值:**`{entrypoint: 'astro/assets/services/squoosh', config?: {}}`<br /> +**默认值:**`{entrypoint: 'astro/assets/services/sharp', config?: {}}`<br /> <Since v="2.1.0" /> </p> @@ -859,7 +835,7 @@ Astro 默认使用 [SmartyPants formatter](https://daringfireball.net/projects/s ## 集成 -用自定义集成来扩展 Astro 功能。你可以用集成来添加框架支持(如 Solid.js)、新功能(如站点地图)和新库支持(如 Partytown 和 Turbolinks)。 +用自定义集成来扩展 Astro 功能。你可以用集成来添加框架支持(如 Solid.js)、新功能(如站点地图)和新库支持(如 Partytown)。 请阅读我们的[集成指南](/zh-cn/guides/integrations-guide/),以帮助开始使用 Astro 集成。 @@ -910,27 +886,6 @@ import tailwind from '@astrojs/tailwind'; Astro 提供了实验性标志,以便用户提前使用新功能。这些标志不保证稳定。 -### experimental.assets - -<p> - -**类型:**`boolean`<br /> -**默认值:**`false`<br /> -<Since v="2.1.0" /> -</p> - -启用对优化和调整图像大小的实验性支持。启用此功能后,将暴露一个新的 `astro:assets` 模块。 - -要启用此功能,请在你的 Astro 配置中将 `experimental.assets` 设置为 `true` : - -```js -{ - experimental: { - assets: true, - }, -} -``` - ### experimental.viewTransitions <p> From a51e03a198149b4bf60ece62dda2ae59aeeddb7c Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 15:38:53 +0800 Subject: [PATCH 11/57] Update directives reference --- .../docs/zh-cn/reference/directives-reference.mdx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/content/docs/zh-cn/reference/directives-reference.mdx b/src/content/docs/zh-cn/reference/directives-reference.mdx index 8bfe89f59d31f..5a5553731a5ad 100644 --- a/src/content/docs/zh-cn/reference/directives-reference.mdx +++ b/src/content/docs/zh-cn/reference/directives-reference.mdx @@ -26,25 +26,22 @@ title: 模板指令参考 ### `class:list` -`class:list={...}` 接收 class 数组,并将其转换为 class 字符串。这是受流行的 @lukeed [clsx](https://github.com/lukeed/clsx)辅助库的启发,但直接内置在 Astro 里。 +`class:list={...}` 接收 class 数组,并将其转换为 class 字符串。这是受流行的 @lukeed [clsx](https://github.com/lukeed/clsx)辅助库的启发。 `class:list` 接收数组,其中有几种不同的可能值: - `string`:添加到 `class` 元素 - `Object`:添加到键值对到 `class` 元素 - `Array`:扁平化 -- `Set`:扁平化 -- `false` 或 `null`:被忽略 +- `false`, `null`, or `undefined`: skipped ```astro <!-- 原先 --> -<span class:list={[ 'hello goodbye', { hello: true, world: true }, new Set([ 'hello', 'friend' ]) ]} /> +<span class:list={[ 'hello goodbye', { world: true }, [ 'friend' ] ]} /> <!-- 输出 --> <span class="hello goodbye world friend"></span> ``` -它会自动删除重复值。 - ### `set:html` `set:html={string}` 将 HTML 字符串注入元素中,类似于设置 `el.innerHTML`。 From 36b6ae1f27812c93613fb0c6960802ff5bc5252f Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 15:55:41 +0800 Subject: [PATCH 12/57] Update integrations reference --- .../reference/integrations-reference.mdx | 84 +++++++++++++++++-- 1 file changed, 76 insertions(+), 8 deletions(-) diff --git a/src/content/docs/zh-cn/reference/integrations-reference.mdx b/src/content/docs/zh-cn/reference/integrations-reference.mdx index e742b404e045e..8d3aff4c63415 100644 --- a/src/content/docs/zh-cn/reference/integrations-reference.mdx +++ b/src/content/docs/zh-cn/reference/integrations-reference.mdx @@ -33,19 +33,24 @@ interface AstroIntegration { injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; }) => void; - 'astro:config:done'?: (options: { config: AstroConfig }) => void | Promise<void>; - 'astro:server:setup'?: (options: { server: vite.ViteDevServer }) => void | Promise<void>; - 'astro:server:start'?: (options: { address: AddressInfo }) => void | Promise<void>; - 'astro:server:done'?: () => void | Promise<void>; - 'astro:build:start'?: () => void | Promise<void>; + 'astro:config:done'?: (options: { config: AstroConfig; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:setup'?: (options: { server: vite.ViteDevServer; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:start'?: (options: { address: AddressInfo; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:server:done'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:build:start'?: (options: { logger: AstroIntegrationLogger; }) => void | Promise<void>; 'astro:build:setup'?: (options: { vite: ViteConfigWithSSR; pages: Map<string, PageBuildData>; target: 'client' | 'server'; + logger: AstroIntegrationLogger; }) => void | Promise<void>; - 'astro:build:generated'?: (options: { dir: URL }) => void | Promise<void>; - 'astro:build:ssr'?: (options: { manifest: SerializedSSRManifestm, entryPoints: Map<RouteData, URL> }) => void | Promise<void>; - 'astro:build:done'?: (options: { dir: URL; routes: RouteData[], pages: { pathname: string }[] }) => void | Promise<void>; + 'astro:build:generated'?: (options: { dir: URL; logger: AstroIntegrationLogger; }) => void | Promise<void>; + 'astro:build:ssr'?: (options: { + manifest: SerializedSSRManifestm; + entryPoints: Map<RouteData, URL>; + logger: AstroIntegrationLogger; + }) => void | Promise<void>; + 'astro:build:done'?: (options: { dir: URL; routes: RouteData[]; logger: AstroIntegrationLogger; }) => void | Promise<void>; }; } ``` @@ -70,6 +75,7 @@ interface AstroIntegration { addWatchFile: (path: URL | string) => void; injectScript: (stage: InjectedScriptStage, content: string) => void; injectRoute: ({ pattern: string, entryPoint: string }) => void; + logger: AstroIntegrationLogger; }) => void; ``` @@ -529,6 +535,68 @@ export default defineConfig({ 这假定你的集成定义是:1)`default` 导出;2)函数。在添加 `astro-integration` 关键字前,请确保符合要求。 ::: +## `AstroIntegrationLogger` + +Astro 日志记录器的实例,用于写日志。此日志记录器使用与 CLI 配置的相同的[日志级别](/zh-cn/reference/cli-reference/#--verbose)。 + +用于写入终端的**可用方法**: +- `logger.info("Message")`; +- `logger.warn("Message")`; +- `logger.error("Message")`; +- `logger.debug("Message")`; + +所有消息都前面带有一个具有相同集成值的标签。 + +```ts title="integration.ts" {8} +import type { AstroIntegration } from "astro"; +export function formatIntegration(): AstroIntegration { + return { + name: "astro-format", + hooks: { + "astro:build:done": (options, { logger }) => { + // do something + logger.info("Integration ready."); + } + } + } +} +``` + +上面的示例将记录一个包含提供的 `info` 消息的日志: + +```shell +[astro-format] Integration ready. +``` + +要使用不同的标签记录一些日志,请使用 `.fork` 方法指定默认 `name` 的替代品: + +```ts title="integration.ts" ".fork" +import type { AstroIntegration } from "astro"; +export function formatIntegration(): AstroIntegration { + return { + name: "astro-format", + hooks: { + "astro:config:done": ({ logger }) => { + // do something + logger.info("Integration ready."); + }, + "astro:build:done": ({ logger }) => { + const buildLogger = logger.fork("astro-format/build"); + // do something + buildLogger.info("Build finished.") + } + } + } +} +``` + +上面的示例将默认生成带有 `[astro-format]` 的日志,并在指定时生成带有 `[astro-format/build]` 的日志: + +```shell +[astro-format] Integration ready. +[astro-format/build] Build finished. +``` + ## 集成排序 所有的集成都是按照配置的顺序运行的。例如,在 `astro.config.*` 中的数组 `[react(), svelte()]`,`react` 将在 `svelte` 之前运行。 From 4c61de7608a0a294683dd2e7cdb083adfa8e8fd5 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 16:10:08 +0800 Subject: [PATCH 13/57] Translate missing-sharp.mdx --- .../zh-cn/reference/errors/missing-sharp.mdx | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 src/content/docs/zh-cn/reference/errors/missing-sharp.mdx diff --git a/src/content/docs/zh-cn/reference/errors/missing-sharp.mdx b/src/content/docs/zh-cn/reference/errors/missing-sharp.mdx new file mode 100644 index 0000000000000..753028d1bbf94 --- /dev/null +++ b/src/content/docs/zh-cn/reference/errors/missing-sharp.mdx @@ -0,0 +1,26 @@ +--- +title: Could not find Sharp. +i18nReady: true +githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/errors/errors-data.ts +--- + +> **MissingSharp**: 找不到 Sharp. 请手动安装 Sharp(`sharp`)到你的项目。 + +## 哪里发生了错误? +Sharp 是 `astro:assets` 的默认图片服务。当使用像 pnpm 这样的[严格的包管理器](https://pnpm.io/pnpm-vs-npm#npms-flat-tree)时,必须手动安装 Sharp 到你的项目中才能使用图片处理。 + +如果你不使用 `astro:assets` 来处理图片,也不想安装 Sharp,你可以配置以下不处理图片的服务: + +```js +import { defineConfig, passthroughImageService } from "astro/config"; +export default defineConfig({ + image: { + service: passthroughImageService(), + }, +}); +``` + +**请参阅:** +- [默认图像服务](/zh-cn/guides/images/#默认图像服务) +- [图像组件](/zh-cn/guides/images/#image--astroassets) +- [图像服务 API](/zh-cn/reference/image-service-reference/) From 3c1f3774ad519e51da87dea0bb868b39761242e5 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 16:13:16 +0800 Subject: [PATCH 14/57] Remove blank line --- src/content/docs/zh-cn/concepts/why-astro.mdx | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/content/docs/zh-cn/concepts/why-astro.mdx b/src/content/docs/zh-cn/concepts/why-astro.mdx index 8d6735de14317..ff267a599fb32 100644 --- a/src/content/docs/zh-cn/concepts/why-astro.mdx +++ b/src/content/docs/zh-cn/concepts/why-astro.mdx @@ -26,9 +26,6 @@ Astro 是**集多功能于一体的 Web 框架**,用于构建**快速、以内 如果你的项目属于第二个“应用”阵营,Astro 可能不是你项目的正确选择... **没关系!** 查看 [Next.js](https://nextjs.org/) 以获得比 Astro 更专注于应用程序的替代方案。 ::: - - - ## 服务器优先 **Astro 尽可能利用服务器渲染而不是客户端渲染。** 这与传统服务器端框架(PHP、WordPress、Laravel、Ruby on Rails等)使用的方法相同,你不需要学习第二种服务端语言。 Astro 仍然使用 HTML、CSS和JavaScript(或TypeScript)。 @@ -38,9 +35,6 @@ SPA模式有它的优势。然而,这些都是以牺牲额外的复杂性和 📚 [进一步了解 **Astro MPA** 架构的独特之处](/zh-cn/concepts/mpa-vs-spa/) - - - ## 默认快速 良好的性能很重要,对于以内容为中心的网站尤其至关重要。事实证明,糟糕的表现会让你失去参与度、转化率和金钱。列如: - 每快 100ms → 转化率增加 1% ([Mobify](https://web.dev/why-speed-matters/), 收入 +$380,000/年) @@ -56,8 +50,6 @@ 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 开发经验如何。 @@ -69,9 +61,6 @@ Astro 的设计比其他UI框架和语言更简单,其中一个重要原因是 我们最喜欢的谚语之一是:**选择加入复杂性。** 我们设计 Astro 是为了尽可能多地从开发人员体验中消除“所需的复杂性”,尤其是你首次加入时。你可以在 Astro中使用 HTML和CSS构建“Hello World”示例网站。然后当你需要构建更强大的功能时,你可以随时获得新功能和 API。 - - - ## 功能齐全且灵活 **Astro 是集多功能于一体的 Web 框架,提供了构建网站所需的一切** Astro 包括组件语法、基于文件的路由、静态资源处理、构建处理、捆绑、优化、数据获取等。你可以在不超过 Astro 核心功能集 的情况下构建出色的网站。 From 35646d97b11e97afc4b16907d8233fced670a232 Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Fri, 25 Aug 2023 20:19:06 +0800 Subject: [PATCH 15/57] Update endpoints --- .../docs/zh-cn/core-concepts/endpoints.mdx | 56 ++++++++----------- 1 file changed, 22 insertions(+), 34 deletions(-) diff --git a/src/content/docs/zh-cn/core-concepts/endpoints.mdx b/src/content/docs/zh-cn/core-concepts/endpoints.mdx index 692061c2f2c29..89124db9d8a41 100644 --- a/src/content/docs/zh-cn/core-concepts/endpoints.mdx +++ b/src/content/docs/zh-cn/core-concepts/endpoints.mdx @@ -18,12 +18,11 @@ Astro 允许你创建自定义端点来提供任何类型的数据。你可以 ```js // 输出: /builtwith.json export async function GET({params, request}) { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ name: 'Astro', - url: 'https://astro.build/', - }), - }; + url: 'https://astro.build/' + }) + ) } ``` @@ -32,11 +31,7 @@ export async function GET({params, request}) { ```ts title="src/pages/astro-logo.png.ts" {6} 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,8 +40,7 @@ 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` 和动态路由 @@ -60,11 +54,10 @@ const usernames = ["张三", "李四", "王五"] 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 () { @@ -86,11 +79,10 @@ export function getStaticPaths () { import type { APIRoute } from 'astro'; export const GET: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ path: new URL(request.url).pathname }) - }; + ) } ``` @@ -159,35 +151,31 @@ export async function GET({ params, request }) { ```ts title="src/pages/methods.json.ts" export const GET: APIRoute = ({ params, request }) => { - return { - body: JSON.stringify({ + return new Response(JSON.stringify({ message: "This was a GET!" }) - } -}; + ) +} export const POST: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: "这是一个 POST 请求!" + return new Response(JSON.stringify({ + message: "This was a POST!" }) - } + ) } export const DELETE: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: "这是一个 DELETE 请求!" + return new Response(JSON.stringify({ + message: "This was a DELETE!" }) - } + ) } export const ALL: APIRoute = ({ request }) => { - return { - body: JSON.stringify({ - message: `这是一个 ${request.method} 请求!` + return new Resonse(JSON.stringify({ + message: `This was a ${request.method}!` }) - } + ) } ``` From 1ac5e0636abd753277f759dfe637185447a1739d Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Sat, 26 Aug 2023 11:31:57 +0800 Subject: [PATCH 16/57] Update endpoints --- .../docs/zh-cn/core-concepts/endpoints.mdx | 21 ++++++++++++------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/content/docs/zh-cn/core-concepts/endpoints.mdx b/src/content/docs/zh-cn/core-concepts/endpoints.mdx index 89124db9d8a41..25c99ba358a84 100644 --- a/src/content/docs/zh-cn/core-concepts/endpoints.mdx +++ b/src/content/docs/zh-cn/core-concepts/endpoints.mdx @@ -18,7 +18,8 @@ Astro 允许你创建自定义端点来提供任何类型的数据。你可以 ```js // 输出: /builtwith.json export async function GET({params, request}) { - return new Response(JSON.stringify({ + return new Response( + JSON.stringify({ name: 'Astro', url: 'https://astro.build/' }) @@ -54,7 +55,8 @@ const usernames = ["张三", "李四", "王五"] export const GET: APIRoute = ({ params, request }) => { const id = params.id; - return new Response(JSON.stringify({ + return new Response( + JSON.stringify({ name: usernames[id] }) ) @@ -79,7 +81,8 @@ export function getStaticPaths () { import type { APIRoute } from 'astro'; export const GET: APIRoute = ({ params, request }) => { - return new Response(JSON.stringify({ + return new Response( + JSON.stringify({ path: new URL(request.url).pathname }) ) @@ -114,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" + } } - }); + ); } ``` From 8b484a830747da2074f0d842650540319bfe7f7e Mon Sep 17 00:00:00 2001 From: liruifengv <liruifeng1024@gmail.com> Date: Sat, 26 Aug 2023 12:59:06 +0800 Subject: [PATCH 17/57] Update view transitions for v3 --- .../docs/zh-cn/guides/view-transitions.mdx | 231 ++++++++++++++---- src/i18n/zh-cn/nav.ts | 2 +- 2 files changed, 182 insertions(+), 51 deletions(-) diff --git a/src/content/docs/zh-cn/guides/view-transitions.mdx b/src/content/docs/zh-cn/guides/view-transitions.mdx index ba3e56061c535..1ee94d5ae99ad 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:name`:允许你覆盖 Astro 的默认元素匹配方式,为一对 DOM 元素 [指定过渡动画名称](#命名过渡动画)。 - `transition:animate`:在用新元素替换旧元素时,允许你通过指定动画类型来覆盖 Astro 的默认动画效果。可以使用 Astro 的 [内置动画指令](#内置的动画指令) 或 [创建自定义动画](#自定义动画)。 - `transition:persist`: 允许你覆盖 Astro 的默认行为。不同于在导航到另一个页面时用将替换旧元素为新元素的方式,该行为则是在导航到另一个页面时 [保留组件和 HTML 元素的状态](#维持状态)。 -## 命名过渡动画 +### 命名过渡动画 在某些情况下,你可能希望自己对相应的且包含视图过渡动画的元素进行标识,那么你可以使用 `transition:name` 指令为一对元素指定一个名称。 @@ -87,9 +93,9 @@ Astro 会自动为在旧页面和新页面中找到的相应元素并分配一