Skip to content

升级到 Astro v3

本指南将帮助你从 Astro v2 迁移到 Astro v3。

¥This guide will help you migrate from Astro v2 to Astro v3.

需要将旧项目升级到 v2?看看我们的 较旧的迁移指南

¥Need to upgrade an older project to v2? See our older migration guide.

¥Upgrade Astro

使用包管理器将项目的 Astro 版本更新到最新版本。如果你正在使用 Astro 集成,请将其更新到最新版本。

¥Update your project’s version of Astro to the latest version using your package manager. If you’re using Astro integrations, please also update those to the latest version.

Terminal window
# Upgrade to Astro v3.x
npm install astro@latest
# Example: upgrade React and Tailwind integrations
npm install @astrojs/react@latest @astrojs/tailwind@latest

Astro v3.0 实验标志已删除

Section titled Astro v3.0 实验标志已删除

¥Astro v3.0 Experimental Flags Removed

astro.config.mjs 中删除以下实验标志:

¥Remove the following experimental flags from astro.config.mjs:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
experimental: {
assets: true,
viewTransitions: true,
},
})

这些功能现在默认可用:

¥These features are now available by default:

  • 查看动画页面转换和持久岛的转换。如果你使用此实验性标志,请参阅 视图转换 API 重大更改和升级建议

  • 用于在 Astro 中使用图片的新图片服务 API astro:assets,包括新的 <Image /> 组件和 getImage() 函数。请阅读详细的 形象升级建议,无论你是否使用此实验性标志,以了解这可能会如何影响你的项目。

详细了解这两个令人兴奋的功能以及 3.0 博客文章 中的更多内容!

¥Read more about these two exciting features and more in the 3.0 Blog post!

¥Astro v3.0 Breaking Changes

Astro v3.0 包含一些重大更改,并删除了一些以前弃用的功能。如果你的项目在升级到 v3.0 后未按预期工作,请查看本指南以了解所有重大更改的概述以及有关如何更新代码库的说明。

¥Astro v3.0 includes some breaking changes, as well as the removal of some previously deprecated features. If your project doesn’t work as expected after upgrading to v3.0, check this guide for an overview of all breaking changes and instructions on how to update your codebase.

请参阅 变更日志 了解完整的发行说明。

¥See the changelog for full release notes.

¥Removed: Support for Node 16

Node 16 计划于 2023 年 9 月终止生命周期。

¥Node 16 is scheduled to reach its End of Life in September 2023.

Astro v3.0 完全放弃了 Node 16 支持,以便所有 Astro 用户都可以利用 Node 更现代的功能。

¥Astro v3.0 drops Node 16 support entirely so that all Astro users can take advantage of Node’s more modern features.

¥What should I do?

检查你的开发环境和部署环境是否都在使用 Node 18.14.1 或更高版本。

¥Check that both your development environment and your deployment environment are using Node 18.14.1 or higher.

  1. Check your local version of Node using:

    Terminal window
    node -v
  2. Check your deployment environment’s own documentation to verify that they support Node 18.

    You can specify Node 18.14.1 for your Astro project either in a dashboard configuration setting or a .nvmrc file.

    .nvmrc
    18.14.1

已删除:支持 TypeScript 4

Section titled 已删除:支持 TypeScript 4

¥Removed: Support for TypeScript 4

在 Astro v2.x 中,tsconfig.json 预设包括对 TypeScript 4.x 和 5.x 的支持。

¥In Astro v2.x, the tsconfig.json presets include support for both TypeScript 4.x and 5.x.

Astro v3.0 更新了 tsconfig.json 预设,仅支持 TypeScript 5.x。Astro 现在假设你使用 TypeScript 5.0(2023 年 3 月),或者你的编辑器包含它(例如 VS Code 1.77)。

¥Astro v3.0 updates the tsconfig.json presets to only support TypeScript 5.x. Astro now assumes that you use TypeScript 5.0 (March 2023), or that your editor includes it (e.g. VS Code 1.77).

¥What should I do?

如果你已在本地安装 TypeScript,请更新至至少 v5.0。

¥If you have installed TypeScript locally, update to at least v5.0.

Terminal window
npm install typescript@latest --save-dev

¥Removed: @astrojs/image

在 Astro v2.x 中,Astro 提供了包含 Astro <Image /><Picture /> 组件的官方映像集成。

¥In Astro v2.x, Astro offered an official image integration that included Astro <Image /> and <Picture /> components.

Astro v3.0 完全从代码库中删除了这种集成。Astro 的新图片解决方案是内置图片服务 API:astro:assets

¥Astro v3.0 removes this integration from the codebase entirely. Astro’s new solution for images is a built-in image services API: astro:assets.

¥What should I do?

从你的项目中删除 @astrojs/image 集成。你不仅需要卸载集成,还需要更新或删除任何导入语句以及现有的 <Image /><Picture /> 组件。你可能还需要配置首选的默认图片处理服务。

¥Remove the @astrojs/image integration from your project. You will need to not only uninstall the integration but also update or remove any import statements and existing <Image /> and <Picture /> components. You might also need to configure a preferred default image processing service.

你可以在我们的图片指南中找到 有关删除旧图片集成的完整分步说明

¥You will find complete, step-by-step instructions for removing the old image integration in our Images guide.

迁移到 astro:assets 还将带来一些你现在可能希望使用的新图片选项和功能。请参阅完整的 v3.0 镜像升级建议 了解完整详细信息!

¥Migrating to astro:assets will also bring some new image options and features that you may now wish to use. Please see the full v3.0 Image Upgrade Advice for full details!

astro.config.mjs
import { defineConfig } from 'astro/config';
import image from '@astrojs/image';
export default defineConfig({
integrations: [
image(),
]
})

¥Removed: <Markdown /> component

在 Astro v1.x 中,Astro 弃用了 <Markdown /> 组件并将其移至外部包中。

¥In Astro v1.x, Astro deprecated the <Markdown /> component and moved it to an external package.

Astro v3.0 完全删除了 @astrojs/markdown-component 包。Astro 的 <Markdown /> 组件将不再在你的项目中工作。

¥Astro v3.0 completely removes the package @astrojs/markdown-component. Astro’s <Markdown /> component will no longer work in your project.

¥What should I do?

删除 @astrojs/markdown-component 的所有实例。

¥Remove all instances of the @astrojs/markdown-component.

src/components/MyAstroComponent.astro
---
import Markdown from '@astrojs/markdown-component';
---

要继续在代码中使用类似的 <Markdown /> 组件,请考虑使用 社区整合,例如 astro-remote。请务必根据集成自身的文档根据需要更新 <Markdown /> 组件导入和属性。

¥To continue using a similar <Markdown /> component in your code, consider using community integrations such as astro-remote. Be sure to update your <Markdown /> component imports and attributes as necessary, according to the integration’s own documentation.

否则,请删除 .astro 文件中对导入 Astro 的 <Markdown /> 组件以及组件本身的所有引用。你需要直接将内容重写为 HTML 或从 .md 文件重写为 import Markdown

¥Otherwise, delete all references to importing Astro’s <Markdown /> component and the component itself in your .astro files. You will need to rewrite your content as HTML directly or import Markdown from a .md file.

¥Removed: deprecated 1.x APIs

在 Astro v1.x 中,Astro 弃用了我们原来的配置设置以及 <style global><script hoist> 支持。然而,为了向后兼容,这些仍然受到支持。

¥In Astro v1.x, Astro deprecated our original configuration settings as well as <style global> and <script hoist> support. However, these were still supported for backwards compatibility.

Astro v3.0 完全删除了这些已弃用的 API。应改用官方支持的 配置设置 以及现代 <style is:global><script> 语法。

¥Astro v3.0 removes these deprecated APIs entirely. The officially supported configuration settings and modern <style is:global> and <script> syntax should be used instead.

¥What should I do?

如果你继续使用 v1.x API,请改用每个功能的新 API:

¥If you are continuing to use v1.x APIs, use the new APIs for each feature instead:

已删除:服务器代码中 Web API 的部分垫片

Section titled 已删除:服务器代码中 Web API 的部分垫片

¥Removed: Partial shims for Web APIs in server code

在 Astro v2.x 中,Astro 为 Web API 提供了部分 shims,例如服务器渲染代码中的 documentlocalStorage。这些垫片通常不完整且不可靠。

¥In Astro v2.x, Astro provided partial shims for Web APIs such as document or localStorage in server-rendered code. These shims were often incomplete and unreliable.

Astro v3.0 完全删除了这些部分垫片。Web API 在服务器渲染的代码中不再可用。

¥Astro v3.0 removes these partial shims entirely. Web APIs are no longer available in server-rendered code.

¥What should I do?

如果你在服务器渲染组件中使用 Web API,则需要将这些 API 的使用设置为有条件的或使用 client:only 客户端指令

¥If you are using Web APIs in server-rendered components, you will need to either make the usage of those APIs conditional or use the client:only client directive.

已删除:内容集合架构中的 astro:content 中的 image

Section titled 已删除:内容集合架构中的 astro:content 中的 image

¥Removed: image from astro:content in content collections schema

在 Astro v2.x 中,内容集合 API 不推荐使用 astro:content 中的 image 导出来在内容集合架构中使用。

¥In Astro v2.x, the content collections API deprecated an image export from astro:content for use in your content collections schemas.

Astro v3.0 完全删除了此导出。

¥Astro v3.0 removes this export entirely.

¥What should I do?

如果你使用的是 astro:content 中已弃用的 image(),请将其删除,因为它不再存在。通过 schemaimage 帮手 验证图片:

¥If you are using the deprecated image() from astro:content, remove it as this no longer exists. Validate images through the image helper from schema instead:

src/content/config.ts
import { defineCollection, z, image } from "astro:content";
import { defineCollection, z } from "astro:content";
defineCollection({
schema: ({ image }) =>
z.object({
image: image(),
}),
});

已删除:0.14 之前的 Shiki 主题名称

Section titled 已删除:0.14 之前的 Shiki 主题名称

¥Removed: pre-0.14 Shiki theme names

在 Astro v2.x 中,一些 Shiki 主题名称已被重命名,但原始名称保留以实现向后兼容。

¥In Astro v2.x, some Shiki theme names had been renamed, but the original names were kept for backwards compatibility.

Astro v3.0 删除了原始名称,转而使用重命名的主题名称。

¥Astro v3.0 removes the original names in favor of the renamed theme names.

¥What should I do?

如果你的项目使用以下任何主题,请将它们重命名为更新后的名称:

¥If your project uses any of the themes below, rename them to their updated name:

  • material-darker -> material-theme-darker

  • material-default -> material-theme

  • material-lighter -> material-theme-lighter

  • material-ocean -> material-theme-ocean

  • material-palenight -> material-theme-palenight

¥Removed: class:list features

在 Astro v2.x 中,class:list 指令 使用了受 clsx 启发的自定义实现,并增加了一些额外功能,如数据去重和 Set 支持。

¥In Astro v2.x, the class:list directive used a custom implementation inspired by clsx with a few extra features like deduplication and Set support.

Astro v3.0 现在直接将 clsx 用于 class:list,不支持数据去重或 Set 值。

¥Astro v3.0 now uses clsx directly for class:list, which does not support deduplication or Set values.

¥What should I do?

将传递给 class:list 指令的任何 Set 元素替换为普通的 Array

¥Replace any Set elements passed to the class:list directive with a plain Array.

src/components/MyAstroComponent.astro
<Component class:list={[
'a',
'b',
new Set(['c', 'd'])
['c', 'd']
]} />

已删除:将 class:list 作为 prop 传递

Section titled 已删除:将 class:list 作为 prop 传递

¥Removed: passing class:list as a prop

在 Astro v2.x 中,class:list 通过 Astro.props['class:list'] 发送到组件。

¥In Astro v2.x, class:list values were sent to components via Astro.props['class:list'].

Astro v3.0 在通过 Astro.props['class'] 发送到组件之前将 class:list 值规范化为字符串

¥Astro v3.0 normalizes class:list values into a string before being sent to components via Astro.props['class']

¥What should I do?

删除任何需要接收 class:list prop 的代码。

¥Remove any code that expects to receive the class:list prop.

src/components/MyAstroComponent.astro
---
import { clsx } from 'clsx';
const { class: className, 'class:list': classList } = Astro.props;
const { class: className } = Astro.props;
---
<div
class:list={[className, classList]}
class:list={[className]}
/>

已删除:camelCase CSS 变量的 kebab-case 转换

Section titled 已删除:camelCase CSS 变量的 kebab-case 转换

¥Removed: kebab-case transform for camelCase CSS variables

在 Astro v2.x 中,传递给 style 属性的 camelCase CSS 变量 被渲染为 camelCase(按书写方式)和 kebab-case(保留以保持向后兼容)。

¥In Astro v2.x, camelCase CSS variables passed to the style attribute were rendered as both camelCase (as written) and kebab-case (kept for backwards compatibility).

Astro v3.0 删除了这些 camelCase CSS 变量名的 kebab-case 转换,并且只渲染原始的 camelCase CSS 变量。

¥Astro v3.0 removes the kebab-case transform for these camelCase CSS variable names, and only the original camelCase CSS variable is rendered.

src/components/MyAstroComponent.astro
---
const myValue = "red"
---
<!-- input -->
<div style={{ "--myValue": myValue }}></div>
<!-- output (Astro 2.x) -->
<div style="--my-value:var(--myValue);--myValue:red"></div>
<!-- output (Astro 3.0) -->
<div style="--myValue:red"></div>

¥What should I do?

如果你依赖 Astro 转换样式中的 kebab-case,请将现有样式更新为 camelCase 以防止缺少样式。例如:

¥If you were relying on Astro to transform kebab-case in your styles, update your existing styles to camelCase to prevent missing styles. For example:

src/components/MyAstroComponent.astro
<style>
div {
color: var(--my-value);
color: var(--myValue);
}
</style>

已删除:getStaticPaths() 返回值的自动展平

Section titled 已删除:getStaticPaths() 返回值的自动展平

¥Removed: automatic flattening of getStaticPaths()’s return value

在 Astro v2.x 中,getStaticPaths() 的返回值自动展平,以允许你返回一个没有错误的数组数组。

¥In Astro v2.x, the return value of getStaticPaths() was automatically flattened to allow you to return an array of arrays without errors.

Astro v3.0 删除了 getStaticPaths() 结果的自动展平。

¥Astro v3.0 removes automatic flattening of getStaticPaths()’s result.

¥What should I do?

如果你返回的是数组数组而不是对象数组(如预期的那样),则现在应该使用 .flatMap.flat 来确保你返回的是扁平数组。

¥If you’re returning an array of arrays instead of an array of objects (as is expected), .flatMap and .flat should now be used to ensure that you are returning a flat array.

如果你需要更新代码,将提供 错误消息表明 getStaticPath() 的返回值必须是对象数组

¥An error message indicating that getStaticPath()’s return value must be an array of objects will be provided if you need to update your code.

移动:astro check 现在需要外部包

Section titled 移动:astro check 现在需要外部包

¥Moved: astro check now requires an external package

在 Astro v2.x 中,astro check 默认包含在 Astro 中,其依赖打包在 Astro 中。无论你是否使用过 astro check,这都意味着更大的包。这也阻止你控制要使用的 TypeScript 版本和 Astro 语言服务器。

¥In Astro v2.x, astro check was included in Astro by default, and its dependencies were bundled in Astro. This meant a larger package whether or not you ever used astro check. This also prevented you from having control over the version of TypeScript and the Astro Language Server to use.

Astro v3.0 将 astro check 命令移出 Astro 核心,现在需要外部包 @astrojs/check。此外,你必须在项目中安装 typescript 才能使用 astro check 命令。

¥Astro v3.0 moves the astro check command out of Astro core and now requires an external package @astrojs/check. Additionally, you must install typescript in your project to use the astro check command.

¥What should I do?

升级到 Astro v3.0 后运行 astro check 命令并按照提示安装所需的依赖,或者手动将 @astrojs/checktypescript 安装到你的项目中。

¥Run the astro check command after upgrading to Astro v3.0 and follow the prompts to install the required dependencies, or manually install @astrojs/check and typescript into your project.

已弃用:build.excludeMiddlewarebuild.split

Section titled 已弃用:build.excludeMiddleware 和 build.split

¥Deprecated: build.excludeMiddleware and build.split

在 Astro v2.x 中,build.excludeMiddlewarebuild.split 用于更改在 SSR 模式下使用适配器时发出特定文件的方式。

¥In Astro v2.x, build.excludeMiddleware and build.split were used to change how specific files were emitted when using an adapter in SSR mode.

Astro v3.0 用新的 SSR 适配器配置选项 替换了这些构建配置选项,以执行相同的任务:edgeMiddlewarefunctionPerRoute

¥Astro v3.0 replaces these build config options with new SSR adapter configuration options to perform the same tasks: edgeMiddleware and functionPerRoute.

¥What should I do?

更新 Astro 配置文件以直接使用适配器配置中的新选项。

¥Update the Astro config file to now use the new options in the adapter configuration directly.

astro.config.mjs
import { defineConfig } from "astro/config";
import vercel from "@astrojs/vercel/serverless";
export default defineConfig({
build: {
excludeMiddleware: true
},
adapter: vercel({
edgeMiddleware: true
}),
});
astro.config.mjs
import { defineConfig } from "astro/config";
import netlify from "@astrojs/netlify/functions";
export default defineConfig({
build: {
split: true
},
adapter: netlify({
functionPerRoute: true
}),
});

¥Deprecated: markdown.drafts

在 Astro v2.x 中,markdown.drafts 配置允许你拥有在运行开发服务器时可用但在生产中未构建的草稿页面。

¥In Astro v2.x, the markdown.drafts configuration allowed you to have draft pages that were available in when running the dev server, but not built in production.

Astro v3.0 弃用此功能,转而采用内容收集方法,通过手动过滤来处理草稿页面,从而可以更好地控制该功能。

¥Astro v3.0 deprecates this feature in favor of the content collections method of handling draft pages by filtering manually instead, which gives more control over the feature.

¥What should I do?

要继续将项目中的某些页面标记为草稿,请使用 draft: true frontmatter 属性代替 迁移到内容集合手动过滤掉页面

¥To continue to mark some pages in your project as drafts, migrate to content collections and manually filter out pages with the draft: true frontmatter property instead.

已弃用:在端点中返回简单对象

Section titled 已弃用:在端点中返回简单对象

¥Deprecated: returning simple object in endpoints

在 Astro v2.x 中,端点可以返回一个简单的对象,该对象将转换为 JSON 响应。

¥In Astro v2.x, endpoints could return a simple object, which would be converted to a JSON response.

Astro v3.0 弃用此行为,转而直接返回 Response 对象。

¥Astro v3.0 deprecates this behavior in favor of returning a Response object directly.

¥What should I do?

更新你的端点以直接返回 Response 对象。

¥Update your endpoints to return a Response object directly.

endpoint.json.ts
export async function GET() {
return { body: { "title": "Bob's blog" }};
return new Response(JSON.stringify({ "title": "Bob's blog" }));
}

如果你确实需要保留以前的格式,则可以使用 ResponseWithEncoding 对象,但将来会被弃用。

¥If you really need to keep the previous format, you can use the ResponseWithEncoding object but will be deprecated in the future.

endpoint.json.ts
export async function GET() {
return { body: { "title": "Bob's blog" } };
return new ResponseWithEncoding({ body: { "title": "Bob's blog" }});
}

更改默认值:tsconfig.json 预设中的 verbatimModuleSyntax

Section titled 更改默认值:tsconfig.json 预设中的 verbatimModuleSyntax

¥Changed default: verbatimModuleSyntax in tsconfig.json presets

在 Astro v2.x 中,verbatimModuleSyntax 设置默认关闭,其 TypeScript 4.x 等效 importsNotUsedAsValuesstrict 预设中启用。

¥In Astro v2.x, the verbatimModuleSyntax setting was off by default, with its TypeScript 4.x equivalent importsNotUsedAsValues being enabled in the strict preset.

在 Astro v3.0 中,每个预设中都启用了 verbatimModuleSyntax

¥In Astro v3.0, verbatimModuleSyntax is enabled in every preset.

¥What should I do?

此选项要求使用 import type 语法导入类型。

¥This option requires that types are imported using the import type syntax.

src/components/MyAstroComponent.astro
---
import { type CollectionEntry, getEntry } from "astro:content";
---

虽然我们建议保持它并正确地使用 type 进行类型导入(如上所示),但如果它导致任何问题,你可以通过在 tsconfig.json 文件中设置 verbatimModuleSyntax: false 来禁用它。

¥While we recommend keeping it on and properly making your type imports with type (as shown above), you can disable it by setting verbatimModuleSyntax: false in your tsconfig.json file if it causes any issues.

tsconfig.json
{
"compilerOptions": {
"verbatimModuleSyntax": false
}
}

¥Changed default: port 3000

在 Astro v2.x 中,Astro 默认在端口 3000 上运行。

¥In Astro v2.x, Astro ran on port 3000 by default.

Astro v3.0 将 默认端口 更改为 4321。🚀

¥Astro v3.0 changes the default port to 4321. 🚀

¥What should I do?

更新对 localhost:3000 的任何现有引用(例如在测试中或在你的 README 中),以反映新端口 localhost:4321

¥Update any existing references to localhost:3000, for example in tests or in your README, to reflect the new port localhost:4321.

更改默认值:import.meta.env.BASE_URL trailingSlash

Section titled 更改默认值:import.meta.env.BASE_URL trailingSlash

¥Changed default: import.meta.env.BASE_URL trailingSlash

在 Astro v2.x 中,import.meta.env.BASE_URL 默认将 base 设置附加到 trailingSlashtrailingSlash: "ignore" 还附加了一个尾随斜杠。

¥In Astro v2.x, import.meta.env.BASE_URL appended your base setting with a trailingSlash by default. trailingSlash: "ignore" also appended a trailing slash.

Astro v3.0 不再默认在 import.meta.env.BASE_URL 后附加斜杠,在设置 trailingSlash: "ignore" 时也不再附加斜杠。(basetrailingSlash: "always"trailingSlash: "never" 结合的现有行为保持不变。)

¥Astro v3.0 no longer appends import.meta.env.BASE_URL with a trailing slash by default, nor when trailingSlash: "ignore" is set. (The existing behavior of base in combination with trailingSlash: "always" or trailingSlash: "never" is unchanged.)

¥What should I do?

如果你的 base 已经有尾随斜杠,则无需更改。

¥If your base already has a trailing slash, no change is needed.

如果你的 base 没有尾随斜杠,如果你希望保留以前的默认(或 trailingSlash: "ignore")行为,请添加一个:

¥If your base does not have a trailing slash, add one if you wish to preserve the previous default (or trailingSlash: "ignore") behavior:

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
base: 'my-base',
base: 'my-base/',
});

更改默认值:compressHTML

Section titled 更改默认值:compressHTML

¥Changed default: compressHTML

在 Astro v2.x 中,当 compressHTML 明确设置为 true 时,Astro 只会压缩你发出的 HTML。默认值为 false

¥In Astro v2.x, Astro only compressed your emitted HTML when compressHTML was explicitly set to true. The default value was false.

Astro v3.0 现在默认压缩发出的 HTML。

¥Astro v3.0 now compresses emitted HTML by default.

¥What should I do?

你现在可以从配置中删除 compressHTML: true,因为这是新的默认行为。

¥You can now remove compressHTML: true from your configuration as this is the new default behavior.

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
compressHTML: true
})

你现在必须将 compressHTML: false 设置为退出 HTML 压缩。

¥You must now set compressHTML: false to opt out of HTML compression.

更改默认值:scopedStyleStrategy

Section titled 更改默认值:scopedStyleStrategy

¥Changed default: scopedStyleStrategy

在 Astro v2.x 中,scopedStyleStrategy 的默认值为 "where"

¥In Astro v2.x, the default value of scopedStyleStrategy was "where".

Astro v3.0 引入了一个新的默认值:"attribute"。默认情况下,现在使用 data-* 属性应用样式。

¥Astro v3.0 introduces a new, default value: "attribute". By default, styles are now applied using data-* attributes.

¥What should I do?

要保留项目当前的 样式范围,请将配置文件更新为之前的默认值:

¥To retain your project’s current style scoping, update the configuration file to the previous default value:

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
scopedStyleStrategy: "where"
})

更改默认值:inlineStyleSheets

Section titled 更改默认值:inlineStyleSheets

¥Changed default: inlineStyleSheets

在 Astro v2.x 中,默认情况下,所有项目样式表都作为链接标签发送。你可以选择每次使用 "always" 将它们内联到 <style> 标签中,或者通过设置 build.inlineStylesheets 配置使用 "auto" 仅内联低于特定大小的样式表。默认设置为 "never"

¥In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to inlining them into <style> tags every time with "always", or to inlining only stylesheets below a certain size with "auto" by setting the build.inlineStylesheets configuration. The default setting was "never".

Astro v3.0 将 inlineStylesheets 的默认值更改为 "auto"。默认情况下,小于 ViteConfig.build.assetsInlineLimit(默认值:4kb)的样式表是内联的。否则,项目样式将在外部样式表中发送。

¥Astro v3.0 changes the default value of inlineStylesheets to "auto". Stylesheets smaller than ViteConfig.build.assetsInlineLimit (default: 4kb) are inlined by default. Otherwise, project styles are sent in external stylesheets.

¥What should I do?

如果你想要保留项目的当前行为,请将 build.inlineStylesheets 设置为之前的默认值 "never"

¥If you want to keep your project’s current behavior, set build.inlineStylesheets to the previous default, "never":

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
build: {
inlineStylesheets: "never"
}
})

更改默认值:图片服务

Section titled 更改默认值:图片服务

¥Changed default: image service

在 Astro v2.x 中,Squoosh 是 默认图片处理服务

¥In Astro v2.x, Squoosh was the default image processing service.

Astro v3.0 现在将 Sharp 作为默认图片处理服务,而是提供使用 Squoosh 的配置选项。

¥Astro v3.0 now includes Sharp as the default image processing service and instead provides a configuration option to use Squoosh.

¥What should I do?

如果你希望继续使用 Squoosh 转换图片,请使用以下内容更新你的配置:

¥If you would prefer to continue to use Squoosh to transform your images, update your config with the following:

astro.config.mjs
import { defineConfig, squooshImageService } from "astro/config";
export default defineConfig({
image: {
service: squooshImageService(),
}
})

改变:HTTP 请求方法案例

Section titled 改变:HTTP 请求方法案例

¥Changed: HTTP request methods case

在 Astro v2.x 中,HTTP 请求方法 使用小写函数名编写: ==getpostputalldel

¥In Astro v2.x, HTTP request methods were written using lowercase function names: get, post, put, all, and del.

Astro v3.0 使用大写函数名,包括 DELETE 而不是 del

¥Astro v3.0 uses uppercase function names, including DELETE instead of del.

¥What should I do?

将所有函数重命名为其大写等效项:

¥Rename all functions to their uppercase equivalent:

  • getGET

  • postPOST

  • putPUT

  • allALL

  • delDELETE

endpoint.ts
export function get() {
export function GET() {
return new Response(JSON.stringify({ "title": "Bob's blog" }));
}

改变:多个 JSX 框架配置

Section titled 改变:多个 JSX 框架配置

¥Changed: Multiple JSX framework configuration

在 Astro v2.x 中,你可以在同一个项目中使用 多个 JSX 框架集成(React、Solid、Preact),而无需识别哪些文件属于哪个框架。

¥In Astro v2.x, you could use multiple JSX framework integrations (React, Solid, Preact) in the same project without needing to identify which files belonged to which framework.

当你安装了多个 JSX 框架集成时,Astro v3.0 现在要求你使用新的 includeexclude 集成配置选项指定要为你的文件使用哪个框架。这使 Astro 能够更好地支持单框架使用以及 React Fast Refresh 等高级功能。

¥Astro v3.0 now requires you to specify which framework to use for your files with new include and exclude integration config options when you have multiple JSX framework integrations installed. This allows Astro to better support single-framework usage, as well as advanced features like React Fast Refresh.

¥What should I do?

如果你在同一个项目中使用多个 JSX 框架,请将 include(以及可选的 exclude)设置为文件和/或文件夹数组。通配符可用于包含多个文件路径。

¥If you are using multiple JSX frameworks in the same project, set include (and optionally exclude) to an array of files and/or folders. Wildcards may be used to include multiple file paths.

我们建议将通用框架组件放在同一文件夹中(例如 /components/react//components/solid/),以便更轻松地指定包含内容,但这不是必需的:

¥We recommend placing common framework components in the same folder (e.g. /components/react/ and /components/solid/) to make specifying your includes easier, but this is not required:

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({
// Enable many frameworks to support all different kinds of components.
// No `include` is needed if you are only using a single framework!
integrations: [
preact({
include: ['**/preact/*']
}),
react({
include: ['**/react/*']
}),
solid({
include: ['**/solid/*'],
}),
]
});

改变:Astro.cookies.get(key) 可以返回 undefined

Section titled 改变:Astro.cookies.get(key) 可以返回 undefined

¥Changed: Astro.cookies.get(key) can return undefined

在 Astro v2.x 中,即使 cookie 不存在,Astro.cookies.get(key) 也始终会返回 AstroCookie 对象。要检查其是否存在,你需要使用 Astro.cookies.has(key)

¥In Astro v2.x, Astro.cookies.get(key) would always return an AstroCookie object, even if the cookie did not exist. To check for its existence, you needed to use Astro.cookies.has(key).

如果 cookie 不存在,Astro v3.0 将为 Astro.cookies.get(key) 返回 undefined

¥Astro v3.0 returns undefined for Astro.cookies.get(key) if the cookie does not exist.

¥What should I do?

此更改不会破坏在使用 Astro.cookies.get(key) 之前检查 Astro.cookie 对象是否存在的任何代码,但现在不再需要。

¥This change will not break any code that checks for the existence of the Astro.cookie object before using Astro.cookies.get(key), but is now no longer required.

你可以安全地删除使用 has() 检查 Astro.cookies 的值是否为 undefined 的任何代码:

¥You can safely remove any code that uses has() to check if the value of Astro.cookies is undefined:

if (Astro.cookies.has(id)) {
const id = Astro.cookies.get(id)!;
}
const id = Astro.cookies.get(id);
if (id) {
}

改变:以编程方式运行 Astro CLI

Section titled 改变:以编程方式运行 Astro CLI

¥Changed: running the Astro CLI programmatically

在 Astro v2.x 中,"astro" 包入口点直接导出并运行 Astro CLI。在实践中不建议以这种方式运行 Astro。

¥In Astro v2.x, the "astro" package entrypoint exported and ran the Astro CLI directly. It is not recommended to run Astro this way in practice.

Astro v3.0 从入口点删除 CLI,并导出一组新的实验性 JavaScript API,包括 dev()build()preview()sync()

¥Astro v3.0 removes the CLI from the entrypoint, and exports a new set of experimental JavaScript APIs, including dev(), build(), preview(), and sync().

¥What should I do?

对于 以编程方式运行 Astro CLI,请使用新的实验性 JavaScript API:

¥To run the Astro CLI programmatically, use the new experimental JavaScript APIs:

import { dev, build } from "astro";
// Start the Astro dev server
const devServer = await dev();
await devServer.stop();
// Build your Astro project
await build();

改变:内部 Astro API 入口点导出路径

Section titled 改变:内部 Astro API 入口点导出路径

¥Changed: internal Astro API entry point export paths

在 Astro v2.x 中,你可以从 astro/internal/*astro/runtime/server/* 导入内部 Astro API。

¥In Astro v2.x, you could import internal Astro APIs from astro/internal/* and astro/runtime/server/*.

Astro v3.0 删除了两个入口点,转而使用现有的 astro/runtime/* 入口点。此外,已为特定于编译器的运行时代码添加了新的 astro/compiler-runtime 导出。

¥Astro v3.0 removes the two entry points in favor of the existing astro/runtime/* entrypoint. Additionally, a new astro/compiler-runtime export has been added for compiler-specific runtime code.

¥What should I do?

这些是 Astro 内部 API 的入口点,不会影响你的项目。但如果你确实使用这些入口点,请按如下所示进行更新:

¥These are entry points for Astro’s internal API and should not affect your project. But if you do use these entrypoints, update as shown below:

import 'astro/internal/index.js';
import 'astro/runtime/server/index.js';
import 'astro/server/index.js';
import 'astro/runtime/server/index.js';
import { transform } from '@astrojs/compiler';
const result = await transform(source, {
internalURL: 'astro/runtime/server/index.js',
internalURL: 'astro/compiler-runtime',
// ...
});

¥Feature Upgrades

¥Upgrade images to v3

Astro v3.0 中的 astro:assets 不再是实验性标志。

¥astro:assets is no longer behind an experimental flag in Astro v3.0.

<Image /> 现在是内置组件,之前的 @astrojs/image 集成已被删除。

¥<Image /> is now a built-in component and the previous @astrojs/image integration has been removed.

当你从早期版本升级 Astro 项目时,这些以及在 Astro 中使用图片的其他伴随更改可能会导致一些重大更改。

¥These and other accompanying changes to using images in Astro may cause some breaking changes when you upgrade your Astro project from an earlier version.

请酌情按照以下说明将 Astro v2.x 项目升级到 v3.0。

¥Please follow the instructions below as appropriate to upgrade an Astro v2.x project to v3.0.

experimental.assets 升级

Section titled 从 experimental.assets 升级

¥Upgrade from experimental.assets

如果你之前启用了 astro:assets 的实验标志,则需要为 Astro v3.0 更新你的项目,该项目现在默认包含资源功能。

¥If you had previously enabled the experimental flag for astro:assets, you will need to update your project for Astro v3.0 which now includes assets features by default.

删除 experimental.assets 标志
Section titled 删除 experimental.assets 标志

¥Remove experimental.assets flag

删除实验标志:

¥Remove the experimental flag:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
experimental: {
assets: true
}
});

如有必要,还可以更新 src/env.d.ts 文件以将 astro/client-image 引用替换为 astro/client

¥If necessary, also update your src/env.d.ts file to replace the astro/client-image reference with astro/client:

src/env.d.ts
/// <reference types="astro/client-image" />
/// <reference types="astro/client" />

¥Remove the ~/assets import alias

默认情况下,astro:assets 不再包含此导入别名。如果你将此别名用于实验资源,则必须将它们转换为相对文件路径或 create your own import aliases

¥This import alias is no longer included by default with astro:assets. If you were using this alias with experimental assets, you must convert them to relative file paths, or create your own import aliases.

src/pages/posts/post-1.astro
---
import rocket from '~/assets/rocket.png';
import rocket from '../../assets/rocket.png';
---
添加对 Cloudflare、Deno、Vercel Edge 和 Netlify Edge 的简单资源支持
Section titled 添加对 Cloudflare、Deno、Vercel Edge 和 Netlify Edge 的简单资源支持

¥Add simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge

Astro v3.0 允许 astro:assets 在 Cloudflare、Deno、Vercel Edge 和 Netlify Edge 中无错误工作,这些产品不支持 Astro 内置的 Squoosh 和 Sharp 图片优化。请注意,Astro 在这些环境中不会执行任何图片转换和处理。但是,你仍然可以享受使用 astro:assets 的其他好处,包括无累积布局偏移 (CLS)、强制的 alt 属性以及一致的创作体验。

¥Astro v3.0 allows astro:assets to work without errors in Cloudflare, Deno, Vercel Edge and Netlify Edge, which do not support Astro’s built-in Squoosh and Sharp image optimization. Note that Astro does not perform any image transformation and processing in these environments. However, you can still enjoy the other benefits of using astro:assets, including no Cumulative Layout Shift (CLS), the enforced alt attribute, and a consistent authoring experience.

如果你之前由于这些限制而避免使用 astro:assets,那么现在可以毫无问题地使用它们。你可以配置无操作图片服务以显式选择加入此行为:

¥If you previously avoided using astro:assets because of these constraints, you can now use them without issues. You can configure the no-op image service to explicitly opt-in to this behavior:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
image: {
service: {
entrypoint: 'astro/assets/services/noop'
}
}
});

¥Decide where to store your images

请参阅图片指南来帮助你决定 在哪里存储你的图片。你可能希望利用新选项来存储图片以及 astro:assets 带来的额外灵活性。例如,现在可以使用标准 Markdown ![alt](src) 语法在 Markdown、MDX 和 Markdoc 中引用项目 src/ 中的相关图片。

¥See the Images guide to help you decide where to store your images. You may wish to take advantage of new options for storing your images with the added flexibility astro:assets brings. For example, relative images from your project src/ can now be referenced in Markdown, MDX, and Markdoc using standard Markdown ![alt](src) syntax.

¥Update existing <img> tags

以前,导入图片会返回一个简单的 string 以及图片的路径。现在,导入的图片资源与以下签名匹配:

¥Previously, importing an image would return a simple string with the path of the image. Now, imported image assets match the following signature:

interface ImageMetadata {
src: string;
width: number;
height: number;
format: string;
}

你必须更新任何现有 <img> 标签(包括任何 UI 框架组件中的图片)的 src 属性,并且你还可以更新现在可从导入的图片中使用的其他属性。

¥You must update the src attribute of any existing <img> tags (including any images in UI framework components) and you may also update other attributes that are now available to you from the imported image.

src/components/MyComponent.astro
---
import rocket from '../images/rocket.svg';
---
<img src={rocket} width="250" height="250" alt="A rocketship in space." />
<img src={rocket.src} width={rocket.width} height={rocket.height} alt="A rocketship in space." />

更新你的 Markdown、MDX 和 Markdoc 文件

Section titled 更新你的 Markdown、MDX 和 Markdoc 文件

¥Update your Markdown, MDX, and Markdoc files

现在可以使用标准 Markdown ![alt](src) 语法在 Markdown、MDX 和 Markdoc 中引用项目 src/ 中的相关图片。

¥Relative images from your project src/ can now be referenced in Markdown, MDX, and Markdoc using standard Markdown ![alt](src) syntax.

这允许你将图片从 public/ 目录移动到项目 src/,现在将在其中对其进行处理和优化。你在 public/ 中的现有映像和远程映像仍然有效,但未通过 Astro 的构建过程进行优化。

¥This allows you to move your images from the public/ directory to your project src/ where they will now be processed and optimized. Your existing images in public/ and remote images are still valid but are not optimized by Astro’s build process.

src/pages/posts/post-1.md
# My Markdown Page
<!-- Local images now possible! -->
![A starry night sky.](../../images/stars.png)
<!-- Keep your images next to your content! -->
![A starry night sky.](./stars.png)

如果你需要对图片属性进行更多控制,我们建议使用 .mdx 文件格式,除了 Markdown 语法之外,它还允许你包含 Astro 的 <Image /> 组件或 JSX <img /> 标记。使用 MDX 集成 向 Astro 添加对 MDX 的支持。

¥If you require more control over your image attributes, we recommend using the .mdx file format, which allows you to include Astro’s <Image /> component or a JSX <img /> tag in addition to the Markdown syntax. Use the MDX integration to add support for MDX to Astro.

¥Remove @astrojs/image

如果你在 Astro v2.x 中使用图片集成,请完成以下步骤:

¥If you were using the image integration in Astro v2.x, complete the following steps:

  1. Remove the @astrojs/image integration.

    You must remove the integration by uninstalling and then removing it from your astro.config.mjs file.

    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import image from '@astrojs/image';
    export default defineConfig({
    integrations: [
    image(),
    ]
    })
  2. Update types (if required).

    If you had special types configured for @astrojs/image in src/env.d.ts, you may need to change them back to the default Astro types if your upgrade to v3 did not complete this step for you.

    src/env.d.ts
    /// <reference types="@astrojs/image/client" />
    /// <reference types="astro/client" />

    Similarly, update tsconfig.json if necessary:

    tsconfig.json
    {
    "compilerOptions": {
    "types": ["@astrojs/image/client"]
    "types": ["astro/client"]
    }
    }
  3. Migrate any existing <Image /> components.

    Change all import statements from @astrojs/image/components to astro:assets in order to use the new built-in <Image /> component.

    Remove any component attributes that are not currently supported image asset properties.

    For example, aspectRatio is no longer supported, as it is now automatically inferred from the width and height attributes.

    src/components/MyComponent.astro
    ---
    import { Image } from '@astrojs/image/components';
    import { Image } from 'astro:assets';
    import localImage from '../assets/logo.png';
    const localAlt = 'The Astro Logo';
    ---
    <Image
    src={localImage}
    width={300}
    aspectRatio="16:9"
    alt={localAlt}
    />
  4. Choose a default image service.

    Sharp is now the default image service used for astro:assets. If you would like to use Sharp, no configuration is required.

    If you would prefer to use Squoosh to transform your images, update your config with the following image.service option:

    astro.config.mjs
    import { defineConfig, squooshImageService } from 'astro/config';
    export default defineConfig({
    image: {
    service: squooshImageService(),
    },
    });

¥Update Content Collections schemas

现在,你可以使用其相对于当前文件夹的路径在 frontmatter 中声明内容集合条目的关联图片,例如博客文章的封面图片。

¥You can now declare an associated image for a content collections entry, such as a blog post’s cover image, in your frontmatter using its path relative to the current folder.

用于内容集合的新 image 辅助程序可让你使用 Zod 验证图片元数据。了解有关 如何在内容集合中使用图片 的更多信息

¥The new image helper for content collections lets you validate the image metadata using Zod. Learn more about how to use images in content collections

在 Astro v3.0 中导航图片导入

Section titled 在 Astro v3.0 中导航图片导入

¥Navigating Image Imports in Astro v3.0

在 Astro v3.0 中,如果你必须保留旧的图片导入行为并需要图片 URL 的字符串表示形式,请在导入时将 ?url 附加到图片路径的末尾。例如:

¥In Astro v3.0, if you have to preserve the old import behavior for images and require a string representation of the image’s URL, append ?url to the end of your image path when importing it. For example:

src/pages/blog/MyImages.astro
---
import Sprite from '../assets/logo.svg?url';
---
<svg>
<use xlink:href={Sprite + '#cart'} />
</svg>

此方法可确保你获取 URL 字符串。请记住,在开发过程中,Astro 使用 src/ 路径,但在构建时,它会生成像 /_astro/cat.a6737dd3.png 这样的散列路径。

¥This approach ensures you obtain the URL string. Keep in mind that during development, Astro uses a src/ path, but upon building, it generates hashed paths like /_astro/cat.a6737dd3.png.

如果你喜欢直接使用图片对象本身,则可以访问 .src 属性。此方法最适合管理 Core Web Vitals 指标的图片尺寸和防止 CLS 等任务。

¥If you prefer to work directly with the image object itself, you can access the .src property. This approach is best for tasks like managing image dimensions for Core Web Vitals metrics and preventing CLS.

如果你要转场到新的导入行为,结合 ?url.src 方法可能是无缝图片处理的正确方法。

¥If you are transitioning into the new import behavior, combining ?url and .src methods might be the right method for seamless image handling.

¥Upgrade view transitions to v3

在 Astro v3.0 中,视图转换不再是实验性标志。

¥View transitions are no longer behind an experimental flag in Astro v3.0.

如果你未在 Astro 2.x 中启用此实验性标志,则这不会对你的项目造成任何重大更改。新的视图转换 API 对你现有的代码没有影响。

¥If you had not enabled this experimental flag in Astro 2.x, this will not cause any breaking changes to your project. The new View Transitions API has no effect on your existing code.

如果你之前使用过实验性视图转换,那么当你从早期版本升级 Astro 项目时,可能会出现一些重大更改。

¥If you were previously using experimental view transitions, there may be some breaking changes when you upgrade your Astro project from an earlier version.

请按照以下说明适当升级使用 experimental.viewTransitions: true 配置的 Astro v2.x 项目到 v3.0。

¥Please follow the instructions below as appropriate to upgrade an Astro v2.x project configured with experimental.viewTransitions: true to v3.0.

experimental.viewTransitions 升级

Section titled 从 experimental.viewTransitions 升级

¥Upgrade from experimental.viewTransitions

如果你之前启用了视图转换的实验标志,则需要将项目更新为 Astro v3.0,现在默认情况下允许视图转换。

¥If you had previously enabled the experimental flag for view transitions, you will need to update your project for Astro v3.0 which now allows view transitions by default.

删除 experimental.viewTransitions 标志
Section titled 删除 experimental.viewTransitions 标志

¥Remove experimental.viewTransitions flag

删除实验标志:

¥Remove the experimental flag:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
experimental: {
viewTransitions: true
}
});

¥Update import source

<ViewTransitions /> 组件已从 astro:components 移至 astro:transitions。更新项目中所有出现的导入源。

¥The <ViewTransitions /> component has been moved from astro:components to astro:transitions. Update the import source across all occurrences in your project.

src/layouts/BaseLayout.astro
---
import { ViewTransitions } from "astro:components astro:transitions"
---
<html lang="en">
<head>
<title>My Homepage</title>
<ViewTransitions />
</head>
<body>
<h1>Welcome to my website!</h1>
</body>
</html>

更新 transition:animate 指令

Section titled 更新 transition:animate 指令

¥Update transition:animate directives

改变:transition:animatemorph 已重命名为 initial。此外,这不再是默认动画。如果未指定 transition:animate 指令,你的动画现在将默认为 fade

¥Changed: The transition:animate value morph has been renamed to initial. Also, this is no longer the default animation. If no transition:animate directive is specified, your animations will now default to fade.

  1. 将所有 morph 动画重命名为 initial

    src/components/MyComponent.astro
    <div transition:name="name" transition:animate="morph initial" />
  2. 要保留以前默认使用 morph 的所有动画,请显式添加 transition:animate="initial"

    src/components/MyComponent.astro
    <div transition:name="name" transition:animate="initial" />
  3. 你可以安全地删除任何明确设置为 fade 的动画。现在这是默认行为:

    src/components/MyComponent.astro
    <div transition:name="name" transition:animate="fade" />

添加:Astro 还支持新的 transition:animatenone。该值可用于页面的 <html> 元素,以禁用整个页面上的动画全页转场。这将仅覆盖没有动画指令的页面元素上的默认动画行为。你仍然可以在单个元素上设置动画,并且这些特定的动画将会发生。

¥Added: Astro also supports a new transition:animate value, none. This value can be used on a page’s <html> element to disable animated full-page transitions on an entire page. This will only override default animation behavior on page elements without an animation directive. You can still set animations on individual elements, and these specific animations will occur.

  1. 你现在可以禁用单个页面上的所有默认转换,仅对显式使用 transition:animate 指令的元素进行动画处理:

    <html transition:animate="none">
    <head></head>
    <body>
    <h1>Hello world!</h1>
    </body>
    </html>

¥Update event names

事件 astro:load 已重命名为 astro:page-load。重命名项目中的所有事件。

¥The event astro:load has been renamed to astro:page-load. Rename all occurrences in your project.

src/components/MyComponent.astro
<script>
document.addEventListener('astro:load astro:page-load', runSetupLogic);
</script>

事件 astro:beforeload 已重命名为 astro:after-swap。重命名项目中的所有事件。

¥The event astro:beforeload has been renamed to astro:after-swap. Rename all occurrences in your project.

src/components/MyComponent.astro
<script>
document.addEventListener('astro:beforeload astro:after-swap', setDarkMode);
</script>

¥Community Resources

知道 Astro v3.0 的好资源吗?编辑这个页面 并在下面添加链接!

¥Know a good resource for Astro v3.0? Edit this page and add a link below!

¥Known Issues

目前没有已知问题。

¥There are currently no known issues.

Astro 中文网 - 粤ICP备13048890号