Skip to content

升级到 Astro v5

本指南将帮助你从 Astro v4 迁移到 Astro v5。

¥This guide will help you migrate from Astro v4 to Astro v5.

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

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

需要查看 v4 文档吗?访问这个 文档站点的旧版本(未维护的 v4.16 快照)

¥Need to see the v4 docs? Visit this older version of the docs site (unmaintained v4.16 snapshot).

¥Upgrade Astro

使用你的包管理器将你项目的 Astro 版本更新为最新版本:

¥Update your project’s version of Astro to the latest version using your package manager:

终端窗口
# Upgrade Astro and official integrations together
npx @astrojs/upgrade

如果需要的话也可以 手动升级你的 Astro 集成,并且可能还需要升级项目中的其他依赖。

¥You can also upgrade your Astro integrations manually if needed, and you may also need to upgrade other dependencies in your project.

Astro v5.0 包含 潜在的重大变化,以及一些功能的删除和弃用。

¥Astro v5.0 includes potentially breaking changes, as well as the removal and deprecation of some features.

如果你的项目在升级到 v5.0 后无法按预期工作,请查看本指南以获取所有重大更改的概述以及如何更新代码库的说明。

¥If your project doesn’t work as expected after upgrading to v5.0, check this guide for an overview of all breaking changes and instructions on how to update your codebase.

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

¥See the Astro changelog for full release notes.

¥Dependency Upgrades

对 Astro 依赖的任何重大升级都可能会导致项目发生重大变化。

¥Any major upgrades to Astro’s dependencies may cause breaking changes in your project.

Astro v5.0 升级到 Vite v6.0 作为开发服务器和生产打包器。

¥Astro v5.0 upgrades to Vite v6.0 as the development server and production bundler.

¥What should I do?

如果你正在使用 Vite 特定的插件、配置或 API,请检查 Vite 迁移指南 的重大更改并根据需要升级你的项目。

¥If you are using Vite-specific plugins, configuration, or APIs, check the Vite migration guide for their breaking changes and upgrade your project as needed.

在 Astro v4.x 中,Astro 为 @astrojs/mdx 集成执行了内部 JSX 处理。

¥In Astro v4.x, Astro performed internal JSX handling for the @astrojs/mdx integration.

Astro v5.0 将处理和渲染 JSX 和 MDX 的责任直接转移到 @astrojs/mdx 包。这意味着 Astro 5.0 不再与旧版本的 MDX 集成兼容。

¥Astro v5.0 moves this responsibility to handle and render JSX and MDX to the @astrojs/mdx package directly. This means that Astro 5.0 is no longer compatible with older versions of the MDX integration.

¥What should I do?

如果你的项目包含 .mdx 文件,则必须将 @astrojs/mdx 升级到最新版本(v4.0.0),以便集成可以正确处理你的 JSX。

¥If your project includes .mdx files, you must upgrade @astrojs/mdx to the latest version (v4.0.0) so that your JSX can be handled properly by the integration.

如果你正在使用带有实验性 Astro 容器 API 的 MDX 服务器渲染器,则必须更新导入以反映新位置:

¥If you are using an MDX server renderer with the experimental Astro Container API you must update the import to reflect the new location:

import mdxRenderer from "astro/jsx/server.js";
import mdxRenderer from "@astrojs/mdx/server.js";
Learn more about using MDX in your project.

¥Legacy

以下功能现在被视为遗留功能。它们应该正常运行,但不再推荐并且处于维护模式。它们将不会看到未来的改进,文档也不会更新。这些功能最终将被弃用,然后完全删除。

¥The following features are now considered legacy features. They should function normally but are no longer recommended and are in maintenance mode. They will see no future improvements and documentation will not be updated. These features will eventually be deprecated, and then removed entirely.

遗留:v2.0 内容集合 API

标题部分 遗留:v2.0 内容集合 API

¥Legacy: v2.0 Content Collections API

在 Astro 4.x 中,使用 Astro v2.0 中首次引入的内容集合 API 定义、查询和渲染内容集合。所有集合条目都是保留的 src/content/ 文件夹中的本地文件。此外,Astro 的 文件名约定以排除构建单个页面 内置于内容集合 API 中。

¥In Astro 4.x, content collections were defined, queried, and rendered using the Content Collections API first introduced in Astro v2.0. All collection entries were local files within the reserved src/content/ folder. Additionally, Astro’s file name convention to exclude building individual pages was built in to the Content Collections API.

Astro 5.0 使用内容层 API 引入了新版本的内容集合,它带来了多项性能改进和附加功能。虽然旧的(遗留的)和新的(内容层 API)集合可以在此版本中继续共存,但可能会对现有的遗留集合产生重大影响。

¥Astro 5.0 introduces a new version of content collections using the Content Layer API which brings several performance improvements and added capabilities. While old (legacy) and new (Content Layer API) collections can continue exist together in this release, there are potentially breaking changes to existing legacy collections.

此版本还删除了在集合条目文件名前加上下划线 (_) 以防止构建路由的选项。

¥This release also removes the option to prefix collection entry file names with an underscore (_) to prevent building a route.

¥What should I do?

我们建议你尽快使用 将任何现有集合转换为新的内容层 API,并使用内容层 API 制作任何新集合。

¥We recommend converting any existing collections to the new Content Layer API as soon as you are able and making any new collections using the Content Layer API.

如果你无法转换收藏,请查阅 遗留集合重大更改,了解现有收藏是否受到影响并需要更新。

¥If you are unable to convert your collections, then please consult the legacy collections breaking changes to see whether your existing collections are affected and require updating.

如果你目前无法对集合进行任何更改,则可以使用 启用 legacy.collections 标志,这将允许你将集合保持在当前状态,直到不再支持旧标志。

¥If you are unable to make any changes to your collections at this time, you can enable the legacy.collections flag which will allow you to keep your collections in their current state until the legacy flag is no longer supported.

Learn more about the updated content collections.

¥Updating existing collections

请参阅以下说明,了解如何更新现有内容集合(type: 'content'type: 'data')以使用内容层 API。

¥See the instructions below for updating an existing content collection (type: 'content' or type: 'data') to use the Content Layer API.

Step-by-step instructions to update a collection
  1. Move the content config file. This file no longer lives within the src/content/ folder. This file should now exist at src/content.config.ts.

  2. Edit the collection definition. Your updated collection requires a loader, and the option to select a collection type is no longer available.

    src/content.config.ts
    import { defineCollection, z } from 'astro:content';
    import { glob } from 'astro/loaders';
    const blog = defineCollection({
    // For content layer you no longer define a `type`
    type: 'content',
    loader: glob({ pattern: '**/[^_]*.md', base: "./src/data/blog" }),
    schema: z.object({
    title: z.string(),
    description: z.string(),
    pubDate: z.coerce.date(),
    updatedDate: z.coerce.date().optional(),
    }),
    });
  3. Change references from slug to id. Content layer collections do not have a reserved slug field. Instead, all updated collections will have an id. You may also need to update dynamic routing file names to match a changed getStaticPaths() parameter:

    src/pages/[id].astro
    ---
    export async function getStaticPaths() {
    const posts = await getCollection('blog');
    return posts.map((post) => ({
    params: { slug: post.slug },
    params: { id: post.id },
    props: post,
    }));
    }
    ---
  4. Switch to the new render() function. Entries no longer have a render() method, as they are now serializable plain objects. Instead, import the render() function from astro:content.

    src/pages/index.astro
    ---
    import { getEntry, render } from 'astro:content';
    const post = await getEntry('blog', params.slug);
    const { Content, headings } = await post.render();
    const { Content, headings } = await render(post);
    ---
    <Content />
对旧版 contentdata 集合的重大更改
标题部分 对旧版 content 和 data 集合的重大更改

¥Breaking changes to legacy content and data collections

默认情况下,使用旧 type 属性(contentdata)且未定义 loader 的集合现在使用内容层 API 的内置 glob() 加载器在后台实现,并具有额外的向后兼容性处理。

¥By default, collections that use the old type property (content or data) and do not define a loader are now implemented under the hood using the Content Layer API’s built-in glob() loader, with extra backward-compatibility handling.

此外,存在临时向后兼容性,以将内容配置文件保留在其原始位置 src/content/config.ts

¥Additionally, temporary backwards compatibility exists for keeping the content config file in its original location of src/content/config.ts.

此向后兼容实现能够模拟旧集合的大多数功能,并且允许许多旧集合继续工作,即使没有更新代码也是如此。但是,有一些差异和限制可能会导致现有集合发生重大变化:

¥This backwards compatibility implementation is able to emulate most of the features of legacy collections and will allow many legacy collections to continue to work even without updating your code. However, there are some differences and limitations that may cause breaking changes to existing collections:

  • 在以前版本的 Astro 中,将为 src/content/ 中的所有文件夹生成集合,即使它们未在 src/content/config.ts 中定义。此行为现已弃用,集合应始终在 src/content.config.ts 中定义。对于现有集合,这些可以只是空声明(例如 const blog = defineCollection({})),Astro 将以与新加载行为兼容的方式为你隐式定义你的旧集合。

  • Markdown 集合条目不支持特殊 layout 字段。此属性仅适用于位于 src/pages/ 中且不太可能位于你的集合条目中的独立页面文件。但是,如果你使用此属性,则现在必须创建包含页面样式的动态路由。

  • 生成的集合的排序顺序是不确定的且与平台相关。这意味着如果你调用 getCollection(),则返回条目的顺序可能与以前不同。如果你需要特定顺序,则必须自己对集合条目进行排序。

  • 不支持 image().refine()。如果你需要验证图片的属性,则需要在页面或组件的运行时执行此操作。

  • getEntry(collection, key)key 参数被类型化为 string,而不是每个条目都有类型。

  • 以前,当使用静态字符串作为键调用 getEntry(collection, key) 时,返回类型不可为空。类型现在包括 undefined,因此你必须在使用结果之前检查条目是否已定义,否则会出现类型错误。

启用 legacy.collections 标志
标题部分 启用 legacy.collections 标志

¥Enabling the legacy.collections flag

如果你尚未准备好更新现有收藏,你可以启用 legacy.collections 标志,现有收藏将继续像以前一样运行。

¥If you are not yet ready to update your existing collections, you can enable the legacy.collections flag and your existing collections will continue to function as before.

¥Deprecated

以下已弃用的功能不再受支持且不再记录。请相应地更新你的项目。

¥The following deprecated features are no longer supported and are no longer documented. Please update your project accordingly.

某些已弃用的功能可能会暂时继续运行,直到完全删除。其他人可能会默默地没有任何效果,或者抛出错误提示你更新代码。

¥Some deprecated features may temporarily continue to function until they are completely removed. Others may silently have no effect, or throw an error prompting you to update your code.

¥Deprecated: Astro.glob()

在 Astro v4.x 中,你可以在 .astro 组件中使用 Astro.glob() 来查询项目中的多个文件。这有一些限制(可以使用的地方、性能等),使用内容集合 API 或 Vite 自己的 import.meta.glob() 中的查询函数通常可以提供更多功能和灵活性。

¥In Astro v4.x, you could use Astro.glob() in your .astro components to query multiple files in your project. This had some limitations (where it could be used, performance, etc.), and using querying functions from the Content Collections API or Vite’s own import.meta.glob() often provided more function and flexibility.

Astro 5.0 弃用 Astro.glob(),转而使用 getCollection() 查询你的集合,使用 import.meta.glob() 查询项目中的其他源文件。

¥Astro 5.0 deprecates Astro.glob() in favor of using getCollection() to query your collections, and import.meta.glob() to query other source files in your project.

¥What should I do?

将所有使用的 Astro.glob() 替换为 import.meta.glob()。请注意,import.meta.glob() 不再返回 Promise,因此你可能必须相应地更新代码。你不应该要求对 通配符模式 进行任何更新。

¥Replace all use of Astro.glob() with import.meta.glob(). Note that import.meta.glob() no longer returns a Promise, so you may have to update your code accordingly. You should not require any updates to your glob patterns.

src/pages/blog.astro
---
const posts = await Astro.glob('./posts/*.md');
const posts = Object.values(import.meta.glob('./posts/*.md', { eager: true }));
---
{posts.map((post) => <li><a href={post.url}>{post.frontmatter.title}</a></li>)}

在适当的情况下,请考虑使用 内容集合 来组织你的内容,它具有自己更新、更高性能的查询功能。

¥Where appropriate, consider using content collections to organize your content, which has its own newer, more performant querying functions.

你可能还希望考虑使用 NPM 中的 glob 包,例如 fast-glob

¥You may also wish to consider using glob packages from NPM, such as fast-glob.

已弃用:functionPerRoute(适配器 API)

标题部分 已弃用:functionPerRoute(适配器 API)

¥Deprecated: functionPerRoute (Adapter API)

在 Astro v4.x 中,你可以选择为项目中定义的每个路由创建一个单独的文件,在构建文件夹中镜像你的 src/pages/ 目录。默认情况下,Astro 发出单个 entry.mjs 文件,该文件负责在每个请求上发出渲染的页面。

¥In Astro v4.x, you could opt into creating a separate file for each route defined in the project, mirroring your src/pages/ directory in the build folder. By default, Astro emitted a single entry.mjs file, which was responsible for emitting the rendered page on each request.

Astro v5.0 删除了退出默认行为的选项。此行为现在是标准的,并且不可配置。

¥Astro v5.0 removes the option to opt out of the default behavior. This behavior is now standard, and non-configurable.

从你的 adapterFeatures 配置中删除 functionPerRoute 属性。它不再可用。

¥Remove the functionPerRoute property from your adapterFeatures configuration. It is no longer available.

my-adapter.mjs
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
}
});
},
},
};
}
Learn more about the Adapter API for building adapter integrations.

已弃用:astro:build:done 钩子上的 routes(集成 API)

标题部分 已弃用:astro:build:done 钩子上的 routes(集成 API)

¥Deprecated: routes on astro:build:done hook (Integration API)

在 Astro v4.x 中,集成从 astro:build:done 钩子访问路由。

¥In Astro v4.x, integrations accessed routes from the astro:build:done hook.

Astro v5.0 弃用传递给此钩子的 routes 数组。相反,它会公开一个新的 astro:routes:resolved 钩子,该钩子在 astro:config:done 之前运行,并且每当开发中的路由发生变化时都会运行。它具有已弃用的 routes 列表的所有相同属性,但 distURL 除外,它仅在构建期间可用。

¥Astro v5.0 deprecates the routes array passed to this hook. Instead, it exposes a new astro:routes:resolved hook that runs before astro:config:done, and whenever a route changes in development. It has all the same properties of the deprecated routes list, except distURL which is only available during build.

¥What should I do?

删除传递给 astro:build:done 的任何 routes 实例并将其替换为新的 astro:routes:resolved 钩子。在新公开的 assets 地图上访问 distURL

¥Remove any instance of routes passed to astro:build:done and replace it with the new astro:routes:resolved hook. Access distURL on the newly exposed assets map:

my-integration.mjs
const integration = () => {
let routes
return {
name: 'my-integration',
hooks: {
'astro:routes:resolved': (params) => {
routes = params.routes
},
'astro:build:done': ({
routes
assets
}) => {
for (const route of routes) {
const distURL = assets.get(route.pattern)
if (distURL) {
Object.assign(route, { distURL })
}
}
console.log(routes)
}
}
}
}
Learn more about the Integration API astro:routes:resolved hook for building integrations.

¥Removed

以下功能现已从代码库中完全删除,不再可用。即使在弃用后,其中一些功能可能仍会继续在你的项目中发挥作用。其他人可能默默地没有任何影响。

¥The following features have now been entirely removed from the code base and can no longer be used. Some of these features may have continued to work in your project even after deprecation. Others may have silently had no effect.

现在包含这些已删除功能的项目将无法构建,并且将不再有任何支持文档提示你删除这些功能。

¥Projects now containing these removed features will be unable to build, and there will no longer be any supporting documentation prompting you to remove these features.

¥Removed: The Lit integration

在 Astro v4.x 中,点燃 是通过 @astrojs/lit 包的核心维护框架库。

¥In Astro v4.x, Lit was a core-maintained framework library through the @astrojs/lit package.

Astro v5.0 删除了集成,并且不会再收到与 5.x 及更高版本兼容的进一步更新。

¥Astro v5.0 removes the integration and it will not receive further updates for compatibility with 5.x and above.

¥What should I do?

你可以通过添加客户端脚本标记继续将 Lit 用于客户端组件。例如:

¥You can continue to use Lit for client components by adding a client-side script tag. For example:

<script>
import "../components/MyTabs";
</script>
<my-tabs title="These are my tabs">...</my-tabs>

如果你有兴趣自己维护 Lit 集成,你可能希望使用 @astrojs/lit 的最后发布版本 作为起点并升级相关软件包。

¥If you’re interested in maintaining a Lit integration yourself, you may wish to use the last published version of @astrojs/lit as a starting point and upgrade the relevant packages.

已删除:hybrid 渲染模式

标题部分 已删除:hybrid 渲染模式

¥Removed: hybrid rendering mode

在 Astro v4.x 中,Astro 提供了三种渲染 output 渲染模式:'static''hybrid''server'

¥In Astro v4.x, Astro provided three rendering output rendering modes: 'static', 'hybrid', and 'server'

Astro v5.0 将 output: 'hybrid'output: 'static' 配置合并为一个配置(现在称为 'static'),其工作方式与之前的混合选项相同。

¥Astro v5.0 merges the output: 'hybrid' and output: 'static' configurations into one single configuration (now called 'static') that works the same way as the previous hybrid option.

不再需要在 Astro 配置中指定 output: 'hybrid' 来使用服务器渲染的页面。新的 output: 'static' 包含此功能。

¥It is no longer necessary to specify output: 'hybrid' in your Astro config to use server-rendered pages. The new output: 'static' has this capability included.

Astro 现在将自动允许你选择退出静态站点中的预渲染,而无需更改你的输出配置。任何页面路由或端点都可以包含 export const prerender = false 以按需进行服务器渲染,而站点的其余部分则是静态生成的。

¥Astro will now automatically allow you to opt out of prerendering in your static site with no change to your output configuration required. Any page route or endpoint can include export const prerender = false to be server-rendered on demand, while the rest of your site is statically generated.

¥What should I do?

如果你的项目使用了混合渲染,你现在必须从 Astro 配置中删除 output: 'hybrid' 选项,因为它不再存在。但是,你的项目不需要进行任何其他更改,并且你不应该有任何重大更改。以前的 'hybrid' 行为现在是默认行为,新名称为 'static'

¥If your project used hybrid rendering, you must now remove the output: 'hybrid' option from your Astro config as it no longer exists. However, no other changes to your project are required, and you should have no breaking changes. The previous 'hybrid' behavior is now the default, under a new name 'static'.

astro.config.mjs
import { defineConfig } from "astro/config";
export default defineConfig({
output: 'hybrid',
});

如果你使用的是 output: 'static'(默认)选项,则可以继续像以前一样使用它。默认情况下,你的所有页面将继续进行预渲染,你将拥有一个完全静态的站点。你的项目不应有任何重大更改。

¥If you were using the output: 'static' (default) option, you can continue to use it as before. By default, all of your pages will continue to be prerendered and you will have a completely static site. You should have no breaking changes to your project.

无论你的项目使用哪种 output 模式,仍需要适配器来部署带有任何服务器渲染页面的 Astro 项目。未包含适配器将导致开发时出现警告,并在构建时出现错误。

¥An adapter is still required to deploy an Astro project with any server-rendered pages, no matter which output mode your project uses. Failure to include an adapter will result in a warning in development and an error at build time.

Learn more about on-demand rendering in Astro.

已删除:Squoosh 图片服务

标题部分 已删除:Squoosh 图片服务

¥Removed: Squoosh image service

在 Astro 4.x 中,你可以将 image.service: squooshImageService() 配置为使用 Squoosh 而不是 Sharp 来转换图片。但是,底层库 libsquoosh 不再维护,并且存在内存和性能问题。

¥In Astro 4.x, you could configure image.service: squooshImageService() to use Squoosh to transform your images instead of Sharp. However, the underlying library libsquoosh is no longer maintained and has memory and performance issues.

Astro 5.0 完全删除了 Squoosh 图片优化服务。

¥Astro 5.0 removes the Squoosh image optimization service entirely.

¥What should I do?

要切换到内置的 Sharp 图片服务,请从 Astro 配置中删除 squooshImageService 导入。默认情况下,你将使用 Sharp 作为 astro:assets

¥To switch to the built-in Sharp image service, remove the squooshImageService import from your Astro config. By default, you will use Sharp for astro:assets.

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

如果你使用像 pnpm 这样的严格包管理器,则可能需要手动安装 sharp 包才能使用 Sharp 图片服务,即使它默认内置在 Astro 中。

¥If you are using a strict package manager like pnpm, you may need to install the sharp package manually to use the Sharp image service, even though it is built into Astro by default.

如果你的适配器不支持 Astro 内置的 Sharp 图片优化,你可以配置 配置无操作图片服务 以允许你使用 <Image /><Picture /> 组件。

¥If your adapter does not support Astro’s built-in Sharp image optimization, you can configure a no-op image service to allow you to use the <Image /> and <Picture /> components.

或者,如果你无法使用 Sharp 图片服务,你可能希望考虑 社区维护的 Squoosh 图片服务

¥Alternatively, you may wish to consider a community-maintained Squoosh image service if you are unable to use the Sharp image service.

¥For adapters

如果你的适配器之前已明确说明其与 Squoosh 的兼容性状态,你现在应该从适配器配置中删除此信息。

¥If your adapter previously precised its compatibility status with Squoosh, you should now remove this information from your adapter configuration.

my-adapter.mjs
supportedAstroFeatures: {
assets: {
isSquooshCompatible: true
}
}

已删除:一些面向公众的类型

标题部分 已删除:一些面向公众的类型

¥Removed: some public-facing types

在 Astro v4.x 中,@types/astro.ts 向用户公开所有类型,无论它们是否仍在积极使用或仅供内部使用。

¥In Astro v4.x, @types/astro.ts exposed all types publicly to users, whether or not they were still actively used or only intended for internal use.

Astro v5.0 重构此文件以删除过时和内部类型。此重构为你的编辑器带来了改进(例如更快的完成速度、更低的内存使用率和更多相关的完成选项)。但是,此重构可能会导致某些项目出现错误,这些项目依赖于不再向公众开放的类型。

¥Astro v5.0 refactors this file to remove outdated and internal types. This refactor brings improvements to your editor (e.g. faster completions, lower memory usage, and more relevant completion options). However, this refactor may cause errors in some projects that have been relying on types that are no longer available to the public.

¥What should I do?

删除现在导致项目出现错误的任何类型,因为你不再有权访问它们。这些主要是以前已弃用和删除的 API,但也可能包括现在内部的类型。

¥Remove any types that now cause errors in your project as you no longer have access to them. These are mostly APIs that have previously been deprecated and removed, but may also include types that are now internal.

¥Experimental Flags

以下实验性标志已在 Astro v5.0 中删除,这些功能可供使用:

¥The following experimental flags have been removed in Astro v5.0 and these features are available for use:

  • env

  • serverIslands

此外,以下实验性标志已被删除,现在是 Astro v5.0 中的默认或推荐行为。

¥Additionally, the following experimental flags have been removed and are now the default or recommended behavior in Astro v5.0.

以下实验性标志已被删除,其相应功能不属于 Astro v5.0。

¥The following experimental flags have been removed and their corresponding features are not part of Astro v5.0.

  • contentCollectionsCache

如果你之前使用过这些实验性标志,请将其删除,并将你的 env 配置移至 Astro 配置的根目录:

¥Remove these experimental flags if you were previously using them, and move your env configuration to the root of your Astro config:

astro.config.mjs
import { defineConfig } from 'astro/config';
export default defineConfig({
experimental: {
directRenderScript: true,
globalRoutePriority: true,
contentLayer: true,
serverIslands: true,
contentCollectionsCache: true,
env: {
schema: {...}
}
},
env: {
schema: {...}
}
})

这些功能在 Astro v5.0 中默认全部可用。

¥These features are all available by default in Astro v5.0.

Read about these exciting features and more in the v5.0 Blog post.

¥Changed Defaults

Astro v5.0 中的某些默认行为已更改,你的项目代码可能需要更新以考虑这些更改。

¥Some default behavior has changed in Astro v5.0 and your project code may need updating to account for these changes.

在大多数情况下,唯一需要采取的行动是检查现有项目的部署并确保它继续按预期运行,并根据需要更新代码。在某些情况下,可能有一个配置设置允许你继续使用以前的默认行为。

¥In most cases, the only action needed is to review your existing project’s deployment and ensure that it continues to function as you expect, making updates to your code as necessary. In some cases, there may be a configuration setting to allow you to continue to use the previous default behavior.

现在默认设置 CSRF 保护

标题部分 现在默认设置 CSRF 保护

¥CSRF protection is now set by default

在 Astro v4.x 中,security.checkOrigin 的默认值为 false。以前,你必须明确将此值设置为 true 才能启用跨站点请求伪造 (CSRF) 保护。

¥In Astro v4.x, The default value of security.checkOrigin was false. Previously, you had to explicitly set this value to true to enable Cross-Site Request Forgery (CSRF) protection.

Astro v5.0 将此选项的默认值更改为 true,并将自动检查 “origin” 标头是否与按需渲染页面中每个请求发送的 URL 匹配。

¥Astro v5.0 changes the default value of this option to true, and will automatically check that the “origin” header matches the URL sent by each request in on-demand rendered pages.

¥What should I do?

如果你之前已配置 security.checkOrigin: true,则不再需要 Astro 配置中的此行。这现在是默认值。

¥If you had previously configured security.checkOrigin: true, you no longer need this line in your Astro config. This is now the default.

要禁用此行为,你必须明确设置 security.checkOrigin: false

¥To disable this behavior, you must explicitly set security.checkOrigin: false.

astro.config.mjs
export default defineConfig({
output: "server",
security: {
checkOrigin: false
}
})

注入路由和重定向的路由优先级顺序

标题部分 注入路由和重定向的路由优先级顺序

¥Route priority order for injected routes and redirects

在 Astro v4.x 中,experimental.globalRoutePriority 是一个可选标志,可确保使用 所有路由的路由优先级顺序规则 对注入的路由、基于文件的路由和重定向进行优先排序。通过不自动优先考虑某些类型的路由并标准化路由优先级顺序,这允许更好地控制项目中的路由。

¥In Astro v4.x, experimental.globalRoutePriority was an optional flag that ensured that injected routes, file-based routes, and redirects were all prioritized using the route priority order rules for all routes. This allowed more control over routing in your project by not automatically prioritizing certain kinds of routes and standardizing the route priority order.

Astro v5.0 删除了这个实验性标志,并将其作为 Astro 中的新默认行为:重定向和注入路由现在与基于文件的项目路由具有同等优先级。

¥Astro v5.0 removes this experimental flag and makes this the new default behavior in Astro: redirects and injected routes are now prioritized equally alongside file-based project routes.

请注意,这已经是 Starlight 中的默认行为,不应影响更新的 Starlight 项目。

¥Note that this was already the default behavior in Starlight, and should not affect updated Starlight projects.

¥What should I do?

如果你的项目包含注入的路由或重定向,请检查你的路由是否按预期构建页面 URL。下面显示了新的预期行为的示例。

¥If your project includes injected routes or redirects, please check that your routes are building page URLs as expected. An example of the new expected behavior is shown below.

在包含以下路由的项目中:

¥In a project containing the following routes:

  • 基于文件的路由:/blog/post/[pid]

  • 基于文件的路由:/[page]

  • Injected route:/blog/[...slug]

  • 重定向:/blog/tags/[tag] -> /[tag]

  • 重定向:/posts -> /blog

将构建以下 URL(而不是遵循 Astro v4.x 的路由优先级顺序):

¥The following URLs will be built (instead of following the route priority order of Astro v4.x):

  • /blog/tags/astro 由重定向到 /tags/[tag](而不是注入的路由 /blog/[...slug])构建

  • /blog/post/0 由基于文件的路由 /blog/post/[pid](而不是注入的路由 /blog/[...slug])构建

  • /posts 由重定向到 /blog(而不是基于文件的路由 /[page])构建

如果发生路由冲突,即两个具有相同路由优先级的路由尝试构建相同的 URL,Astro 将记录一条警告,以识别冲突的路由。

¥In the event of route collisions, where two routes of equal route priority attempt to build the same URL, Astro will log a warning identifying the conflicting routes.

Read more about the route priority order rules.

<script> 标签直接按声明方式渲染

标题部分 &lt;script&gt; 标签直接按声明方式渲染

¥<script> tags are rendered directly as declared

在 Astro v4.x 中,experimental.directRenderScript 是一个可选标志,用于直接渲染 .astro 文件中声明的 <scripts>(包括现有功能,如 TypeScript、导入 node_modules 和数据去重脚本)。此策略可防止脚本在未使用的地方执行。

¥In Astro v4.x, experimental.directRenderScript was an optional flag to directly render <scripts> as declared in .astro files (including existing features like TypeScript, importing node_modules, and deduplicating scripts). This strategy prevented scripts from being executed in places where they were not used.

Astro 5.0 删除了这个实验性标志,并将其作为 Astro 中的新默认行为:脚本不再提升到 <head>,页面上的多个脚本不再打包在一起,并且 <script> 标签可能会干扰 CSS 样式。

¥Astro 5.0 removes this experimental flag and makes this the new default behavior in Astro: scripts are no longer hoisted to the <head>, multiple scripts on a page are no longer bundled together, and a <script> tag may interfere with CSS styling.

¥What should I do?

请检查你的 <script> 标签并确保它们按预期运行。

¥Please review your <script> tags and ensure they behave as desired.

Read more about using script tags in Astro.

¥Breaking Changes

以下更改被视为 Astro v5.0 中的重大更改。重大更改可能会或可能不会提供临时的向后兼容性。如果你正在使用这些功能,则可能必须按照每个条目中的建议更新代码。

¥The following changes are considered breaking changes in Astro v5.0. Breaking changes may or may not provide temporary backwards compatibility. If you were using these features, you may have to update your code as recommended in each entry.

已重命名:<ViewTransitions /> 组件

标题部分 已重命名:&lt;ViewTransitions /&gt; 组件

¥Renamed: <ViewTransitions /> component

在 Astro 4.x 中,Astro 的 View Transitions API 包含一个 <ViewTransitions /> 路由组件,以启用客户端路由、页面转换等。

¥In Astro 4.x, Astro’s View Transitions API included a <ViewTransitions /> router component to enable client-side routing, page transitions, and more.

Astro 5.0 将此组件重命名为 <ClientRouter />,以阐明该组件在 API 中的作用。这更清楚地表明,你从 Astro 的 <ClientRouter /> 路由组件获得的功能与基于 CSS 的原生 MPA 路由略有不同。

¥Astro 5.0 renames this component to <ClientRouter /> to clarify the role of the component within the API. This makes it more clear that the features you get from Astro’s <ClientRouter /> routing component are slightly different from the native CSS-based MPA router.

功能未发生任何变化。此组件仅更改了名称。

¥No functionality has changed. This component has only changed its name.

¥What should I do?

ClientRouter 替换所有出现的 ViewTransitions 导入和组件:

¥Replace all occurences of the ViewTransitions import and component with ClientRouter:

src/layouts/MyLayout.astro
import { ViewTransitions } from 'astro:transitions';
import { ClientRouter } from 'astro:transitions';
<html>
<head>
...
<ViewTransitions />
<ClientRouter />
</head>
</html>

改变:TypeScript 配置

标题部分 改变:TypeScript 配置

¥Changed: TypeScript configuration

在 Astro v4.x 中,Astro 依赖 src/env.d.ts 文件进行类型推断和定义依赖于生成类型的功能的模块。

¥In Astro v4.x, Astro relied on a src/env.d.ts file for type inferencing and defining modules for features that relied on generated types.

Astro 5.0 改为使用 .astro/types.d.ts 文件进行类型推断,现在建议在 tsconfig.json 中设置 includeexclude,以从 Astro 类型中受益并避免检查构建的文件。

¥Astro 5.0 instead uses a .astro/types.d.ts file for type inferencing, and now recommends setting include and exclude in tsconfig.json to benefit from Astro types and avoid checking built files.

运行 astro sync 不再创建或更新 src/env.d.ts,因为它不是类型检查标准 Astro 项目所必需的。

¥Running astro sync no longer creates, nor updates, src/env.d.ts as it is not required for type-checking standard Astro projects.

¥What should I do?

要将你的项目更新为 Astro 推荐的 TypeScript 设置,请将以下 includeexclude 属性添加到你现有的 tsconfig.json

¥To update your project to Astro’s recommended TypeScript settings, add the following include and exclude properties to your existing tsconfig.json:

tsconfig.json
{
"extends": "astro/tsconfigs/base",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}

请注意,仅当你添加了自定义配置或未使用 tsconfig.json 文件时,才需要 src/env.d.ts

¥Note that src/env.d.ts is only necessary if you have added custom configurations, or if you’re not using a tsconfig.json file.

标题部分 改变:HTML 表单提交的操作不再使用 cookie 重定向

¥Changed: Actions submitted by HTML forms no longer use cookie redirects

在 Astro 4.x 中,从 HTML 表单调用的操作将触发重定向,并使用 cookie 转发结果。这导致了大型表单错误和返回值超出基于 cookie 的存储 4 KB 限制的问题。

¥In Astro 4.x, actions called from an HTML form would trigger a redirect with the result forwarded using cookies. This caused issues for large form errors and return values that exceeded the 4 KB limit of cookie-based storage.

Astro 5.0 现在将操作结果渲染为 POST 结果,无需任何转发。当用户尝试刷新页面时,这将引入 “确认表单重新提交?” 对话框,但它不再对操作返回值施加 4 KB 的限制。

¥Astro 5.0 now renders the result of an action as a POST result without any forwarding. This will introduce a “confirm form resubmission?” dialog when a user attempts to refresh the page, though it no longer imposes a 4 KB limit on action return value.

¥What should I do?

你应该更新依赖于重定向的操作结果的处理,并可选择使用中间件解决 “确认表单重新提交?” 对话框。

¥You should update handling for action results that relies on redirects, and optionally address the “confirm form resubmission?” dialog with middleware.

出错时重定向到上一条路由
标题部分 出错时重定向到上一条路由

¥To redirect to the previous route on error

如果你的 HTML 表单操作定向到不同的路由(即 action={"/success-page" + actions.name}),Astro 将不再在出错时重定向到上一个路由。你可以使用 Astro 组件中的重定向手动实现此行为。此示例在成功时重定向到新路由,否则处理当前页面上的错误:

¥If your HTML form action is directed to a different route (i.e. action={"/success-page" + actions.name}), Astro will no longer redirect to the previous route on error. You can implement this behavior manually using redirects from your Astro component. This example instead redirects to a new route on success, and handles errors on the current page otherwise:

src/pages/newsletter.astro
---
import { actions } from 'astro:actions';
const result = Astro.getActionResult(actions.newsletter);
if (!result?.error) {
// Embed relevant result data in the URL if needed
// example: redirect(`/confirmation?email=${result.data.email}`);
return redirect('/confirmation');
}
---
<form method="POST" action={'/confirmation' + actions.newsletter}>
<label>E-mail <input required type="email" name="email" /></label>
<button>Sign up</button>
</form>
(可选)刷新时删除确认对话框
标题部分 (可选)刷新时删除确认对话框

¥(Optional) To remove the confirm dialog on refresh

要在刷新时解决 “确认表单重新提交?” 对话框,或要在会话之间保留操作结果,你现在可以使用 从中间件自定义操作结果处理

¥To address the “confirm form resubmission?” dialog on refresh, or to preserve action results across sessions, you can now customize action result handling from middleware.

我们建议使用会话存储提供程序 如我们的 Netlify Blob 示例中所述。但是,如果你更喜欢 4.X 中的 cookie 转发行为并接受 4 KB 大小限制,则可以按照此示例代码片段中所示的模式实现:

¥We recommend using a session storage provider as described in our Netlify Blob example. However, if you prefer the cookie forwarding behavior from 4.X and accept the 4 KB size limit, you can implement the pattern as shown in this sample snippet:

src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { getActionContext } from 'astro:actions';
export const onRequest = defineMiddleware(async (context, next) => {
// Skip requests for prerendered pages
if (context.isPrerendered) return next();
const { action, setActionResult, serializeActionResult } = getActionContext(context);
// If an action result was forwarded as a cookie, set the result
// to be accessible from `Astro.getActionResult()`
const payload = context.cookies.get('ACTION_PAYLOAD');
if (payload) {
const { actionName, actionResult } = payload.json();
setActionResult(actionName, actionResult);
context.cookies.delete('ACTION_PAYLOAD');
return next();
}
// If an action was called from an HTML form action,
// call the action handler and redirect with the result as a cookie.
if (action?.calledFrom === 'form') {
const actionResult = await action.handler();
context.cookies.set('ACTION_PAYLOAD', {
actionName: action.name,
actionResult: serializeActionResult(actionResult),
});
if (actionResult.error) {
// Redirect back to the previous page on error
const referer = context.request.headers.get('Referer');
if (!referer) {
throw new Error('Internal: Referer unexpectedly missing from Action POST request.');
}
return context.redirect(referer);
}
// Redirect to the destination page on success
return context.redirect(context.originPathname);
}
return next();
})

改变:compiledContent() 现在是一个异步函数

标题部分 改变:compiledContent() 现在是一个异步函数

¥Changed: compiledContent() is now an async function

在 Astro 4.x 中,顶层 await 包含在 Markdown 模块中。这导致 Markdown 中的自定义图片服务和图片出现一些问题,从而导致 Node 突然退出且没有错误消息。

¥In Astro 4.x, top level await was included in Markdown modules. This caused some issues with custom image services and images inside Markdown, causing Node to suddenly exit with no error message.

Astro 5.0 使 Markdown 导入上的 compiledContent() 属性成为异步函数,需要 await 来解析内容。

¥Astro 5.0 makes the compiledContent() property on Markdown import an async function, requiring an await to resolve the content.

¥What should I do?

更新你的代码以在调用 compiledContent() 时使用 await

¥Update your code to use await when calling compiledContent().

src/pages/post.astro
---
import * as myPost from "../blog/post.md";
const content = myPost.compiledContent();
const content = await myPost.compiledContent();
---
<Fragment set:html={content} />
Read more about the compiledContent() function for returning compiled Markdown.

改变:astro:content 不再能在客户端上使用

标题部分 改变:astro:content 不再能在客户端上使用

¥Changed: astro:content can no longer be used on the client

在 Astro 4.x 中,可以在客户端上访问 astro:content 模块。

¥In Astro 4.x, it was possible to access the astro:content module on the client.

Astro 5.0 删除了此访问权限,因为它从未有意暴露给客户端使用。以这种方式使用 astro:content 有限制和臃肿的客户端包。

¥Astro 5.0 removes this access as it was never intentionally exposed for client use. Using astro:content this way had limitations and bloated client bundles.

¥What should I do?

如果你当前在客户端中使用 astro:content,请将所需的数据通过 props 传递给客户端组件:

¥If you are currently using astro:content in the client, pass the data you need through props to your client components instead:

src/pages/blog.astro
---
import { getCollection } from 'astro:content';
import ClientComponent from '../components/ClientComponent';
const posts = await getCollection('blog');
const postsData = posts.map(post => post.data);
---
<ClientComponent posts={postsData} />
Read more about the astro:content API.

已重命名:Shiki css-variables 主题颜色标记名称

标题部分 已重命名:Shiki css-variables 主题颜色标记名称

¥Renamed: Shiki css-variables theme color token names

在 Astro v4.x 中,Shiki css-variables 主题分别使用 --astro-code-color-text--astro-code-color-background 标记来设置代码块的前景色和背景色。

¥In Astro v4.x, the Shiki css-variables theme used the --astro-code-color-text and --astro-code-color-background tokens for styling the foreground and background colors of code blocks respectively.

Astro v5.0 分别将它们重命名为 --astro-code-foreground--astro-code-background,以更好地与 Shiki v1 默认值保持一致。

¥Astro v5.0 renames them to --astro-code-foreground and --astro-code-background respectively to better align with the Shiki v1 defaults.

¥What should I do?

你可以在项目中执行全局查找和替换以迁移到新的令牌名称。

¥You can perform a global find and replace in your project to migrate to the new token names.

src/styles/global.css
:root {
--astro-code-color-text: #000;
--astro-code-color-background: #fff;
--astro-code-foreground: #000;
--astro-code-background: #fff;
}
Read more about syntax highlighting in Astro.

改变:用于高亮代码块的内部 Shiki rehype 插件

标题部分 改变:用于高亮代码块的内部 Shiki rehype 插件

¥Changed: internal Shiki rehype plugin for highlighting code blocks

在 Astro 4.x 中,Astro 的内部 Shiki rehype 插件将代码块高亮为 HTML。

¥In Astro 4.x, Astro’s internal Shiki rehype plugin highlighted code blocks as HTML.

Astro 5.0 更新了此插件以将代码块高亮为 hast。这允许更直接的 Markdown 和 MDX 处理并提高构建项目时的性能。但是,这可能会导致现有 Shiki 转换器出现问题。

¥Astro 5.0 updates this plugin to highlight code blocks as hast. This allows a more direct Markdown and MDX processing and improves the performance when building the project. However, this may cause issues with existing Shiki transformers.

¥What should I do?

如果你使用传递给 markdown.shikiConfig.transformers 的 Shiki 转换器,则必须确保它们不使用 postprocess 钩子。此钩子不再在 .md.mdx 文件中的代码块上运行。(有关更多信息,请参阅 Shiki 关于转换器钩子的文档)。

¥If you are using Shiki transformers passed to markdown.shikiConfig.transformers, you must make sure they do not use the postprocess hook. This hook no longer runs on code blocks in .md and .mdx files. (See the Shiki documentation on transformer hooks for more information).

.mdoc 文件中的代码块和 Astro 的内置 <Code /> 组件不使用内部 Shiki rehype 插件,不受影响。

¥Code blocks in .mdoc files and Astro’s built-in <Code /> component do not use the internal Shiki rehype plugin and are unaffected.

Read more about syntax highlighting in Astro.

改变:Markdown 和 MDX 页面的自动 charset=utf-8 行为

标题部分 改变:Markdown 和 MDX 页面的自动 charset=utf-8 行为

¥Changed: Automatic charset=utf-8 behavior for Markdown and MDX pages

在 Astro 4.0 中,Markdown 和 MDX 页面(位于 src/pages/ 中)自动在 Content-Type 标头中使用 charset=utf-8 进行响应,这允许在你的页面中渲染非 ASCII 字符。

¥In Astro 4.0, Markdown and MDX pages (located in src/pages/) automatically responded with charset=utf-8 in the Content-Type header, which allowed rendering non-ASCII characters in your pages.

Astro 5.0 更新了行为以改为添加 <meta charset="utf-8"> 标签,并且仅适用于不使用 Astro 的特殊 layout frontmatter 属性的页面。对于 MDX 页面,同样,如果 MDX 内容未导入封装 Layout 组件,Astro 只会添加标签。

¥Astro 5.0 updates the behaviour to add the <meta charset="utf-8"> tag instead, and only for pages that do not use Astro’s special layout frontmatter property. Similarly for MDX pages, Astro will only add the tag if the MDX content does not import a wrapping Layout component.

如果你的 Markdown 或 MDX 页面使用 layout frontmatter 属性,或者如果 MDX 页面内容导入了封装 Layout 组件,则 HTML 编码将由指定的布局组件处理,并且默认情况下不会将 <meta charset="utf-8"> 标签添加到你的页面。

¥If your Markdown or MDX pages use the layout frontmatter property, or if the MDX page content imports a wrapping Layout component, then the HTML encoding will be handled by the designated layout component instead, and the <meta charset="utf-8"> tag will not be added to your page by default.

¥What should I do?

如果你需要 charset=utf-8 才能正确渲染页面,请确保你的布局组件包含 <meta charset="utf-8"> 标记。如果你还没有这样做,你可能需要添加它。

¥If you require charset=utf-8 to render your page correctly, make sure that your layout components contain the <meta charset="utf-8"> tag. You may need to add this if you have not already done so.

Read more about Markdown layouts.

改变:在备注和 rehype 插件中附加了 Astro 特定的元数据

标题部分 改变:在备注和 rehype 插件中附加了 Astro 特定的元数据

¥Changed: Astro-specific metadata attached in remark and rehype plugins

在 Astro 4.x 中,remark 和 rehype 插件中附加到 vfile.data 的 Astro 特定元数据附加在不同位置,名称不一致。

¥In Astro 4.x, the Astro-specific metadata attached to vfile.data in remark and rehype plugins was attached in different locations with inconsistent names.

Astro 5 清理了 API,元数据现在重命名如下:

¥Astro 5 cleans up the API and the metadata is now renamed as below:

  • vfile.data.__astroHeadings -> vfile.data.astro.headings

  • vfile.data.imagePaths -> vfile.data.astro.imagePaths

imagePaths 的类型也已从 Set<string> 更新为 string[]vfile.data.astro.frontmatter 元数据保持不变。

¥The types of imagePaths has also been updated from Set<string> to string[]. The vfile.data.astro.frontmatter metadata is left unchanged.

¥What should I do?

虽然我们不认为这些 API 是公开的,但想要重用 Astro 元数据的 remark 和 rehype 插件可以访问它们。如果你正在使用这些 API,请确保在新位置访问它们。

¥While we don’t consider these APIs public, they can be accessed by remark and rehype plugins that want to re-use Astro’s metadata. If you are using these APIs, make sure to access them in the new locations.

改变:图片端点配置

标题部分 改变:图片端点配置

¥Changed: image endpoint configuration

在 Astro 4.x 中,你可以在 image 配置中设置一个端点以用于图片优化。

¥In Astro 4.x, you could set an endpoint in your image configuration to use for image optimization.

Astro 5.0 允许你自定义 image.endpoint 配置的 routeentrypoint。这在默认路由 /_image 与现有路由或本地服务器设置冲突的特殊情况下很有用。

¥Astro 5.0 allows you to customize a route and entrypoint of the image.endpoint config. This can be useful in niche situations where the default route /_image conflicts with an existing route or your local server setup.

¥What should I do?

如果你之前已自定义 image.endpoint,请将此端点移动到新的 endpoint.entrypoint 属性。或者,你可以自定义 route

¥If you had previously customized image.endpoint, move this endpoint to the new endpoint.entrypoint property. Optionally, you may customize a route:

astro.config.mjs
import { defineConfig } from "astro/config";
defineConfig({
image: {
endpoint: './src/image-endpoint.ts',
endpoint: {
route: "/image",
entrypoint: "./src/image_endpoint.ts"
}
},
})

改变:build.clientbuild.server 解析行为

标题部分 改变:build.client 和 build.server 解析行为

¥Changed: build.client and build.server resolve behavior

在 Astro v4.x 中,build.clientbuild.server 选项被记录为与 outDir 选项相对解析,但它并不总是按预期工作。

¥In Astro v4.x, the build.client and build.server options were documented to resolve relatively from the outDir option, but it didn’t always work as expected.

Astro 5.0 修复了从 outDir 选项正确解析的行为。例如,如果 outDir 设置为 ./dist/nested/,则默认情况下:

¥Astro 5.0 fixes the behavior to correctly resolve from the outDir option. For example, if outDir is set to ./dist/nested/, then by default:

  • build.client 将解析为 <root>/dist/nested/client/

  • build.server 将解析为 <root>/dist/nested/server/

以前,这些值解析不正确:

¥Previously the values were incorrectly resolved:

  • build.client 已解析为 <root>/dist/nested/dist/client/

  • build.server 已解析为 <root>/dist/nested/dist/server/

¥What should I do?

如果你依赖以前的构建路径,请确保你的项目代码已更新为新的构建路径。

¥If you were relying on the previous build paths, make sure that your project code is updated to the new build paths.

改变:Vite 不再处理配置文件中的 JS 依赖

标题部分 改变:Vite 不再处理配置文件中的 JS 依赖

¥Changed: JS dependencies in config file are no longer processed by Vite

在 Astro 4.x 中,本地链接的 JS 依赖(例如 npm link、monorepo 等)在由 Astro 配置文件导入时能够使用 Vite 功能(如 import.meta.glob)。

¥In Astro 4.x, locally-linked JS dependencies (e.g. npm link, in a monorepo, etc) were able to use Vite features like import.meta.glob when imported by the Astro config file.

Astro 5 更新了 Astro 配置加载流程,以忽略使用 Vite 处理本地链接的 JS 依赖。导出原始 TypeScript 文件的依赖不受影响。相反,这些 JS 依赖通常会由 Node.js 运行时以与 node_modules 中的其他依赖相同的方式导入。

¥Astro 5 updates the Astro config loading flow to ignore processing locally-linked JS dependencies with Vite. Dependencies exporting raw TypeScript files are unaffected. Instead, these JS dependencies will be normally imported by the Node.js runtime the same way as other dependencies from node_modules.

进行此更改是因为之前的行为导致集成作者感到困惑,他们针对本地工作但发布时不起作用的包进行了测试。它还限制使用仅 CJS 依赖,因为 Vite 要求代码为 ESM。虽然此更改仅影响 JS 依赖,但也建议软件包尽可能导出 JavaScript 而不是原始 TypeScript,以防止意外使用 Vite 特定功能,因为它是 Astro 配置加载流程的实现细节。

¥This change was made as the previous behavior caused confusion among integration authors who tested against a package that worked locally, but not when published. It also restricted using CJS-only dependencies because Vite required the code to be ESM. While this change only affects JS dependencies, it’s also recommended for packages to export JavaScript instead of raw TypeScript where possible to prevent accidental Vite-specific usage as it’s an implementation detail of Astro’s config loading flow.

¥What should I do?

确保在运行 Astro 项目之前构建了本地链接的 JS 依赖。然后,配置加载应该像以前一样工作。

¥Make sure your locally-linked JS dependencies are built before running your Astro project. Then, the config loading should work as before.

改变:paginate() 返回的 URL

标题部分 改变:paginate() 返回的 URL

¥Changed: URLs returned by paginate()

在 Astro v4.x 中,paginate()(例如 page.url.nextpage.url.first 等)返回的 URL 不包含 Astro 配置中为 base 设置的值。你必须手动将为 base 配置的值添加到 URL 路径的前面。

¥In Astro v4.x, the URL returned by paginate() (e.g. page.url.next, page.url.first, etc.) did not include the value set for base in your Astro config. You had to manually prepend your configured value for base to the URL path.

Astro 5.0 自动将 base 值包含在 page.url 中。

¥Astro 5.0 automatically includes the base value in page.url.

¥What should I do?

如果你正在为这些 URL 使用 paginate() 函数,请删除任何现有的 base 值,因为它现在已为你添加:

¥If you are using the paginate() function for these URLs, remove any existing base value as it is now added for you:

---
export async function getStaticPaths({ paginate }) {
const astronautPages = [{
astronaut: 'Neil Armstrong',
}, {
astronaut: 'Buzz Aldrin',
}, {
astronaut: 'Sally Ride',
}, {
astronaut: 'John Glenn',
}];
return paginate(astronautPages, { pageSize: 1 });
}
const { page } = Astro.props;
// `base: /'docs'` configured in `astro.config.mjs`
const prev = "/docs" + page.url.prev;
const prev = page.url.prev;
---
<a id="prev" href={prev}>Back</a>
Read more about pagination in Astro.

改变:非布尔 HTML 属性值

标题部分 改变:非布尔 HTML 属性值

¥Changed: non-boolean HTML attribute values

在 Astro v4.x 中,非 布尔 HTML 属性 在渲染为 HTML 时可能未包含其值。

¥In Astro v4.x, non-boolean HTML attributes may not have included their values when rendered to HTML.

Astro v5.0 将值明确渲染为 ="true"="false",以匹配浏览器中的正确属性处理。

¥Astro v5.0 renders the values explicitly as ="true" or ="false", matching proper attribute handling in browsers.

在以下 .astro 示例中,只有 allowfullscreen 是布尔属性:

¥In the following .astro examples, only allowfullscreen is a boolean attribute:

src/pages/index.astro
<!-- `allowfullscreen` is a boolean attribute -->
<p allowfullscreen={true}></p>
<p allowfullscreen={false}></p>
<!-- `inherit` is *not* a boolean attribute -->
<p inherit={true}></p>
<p inherit={false}></p>
<!-- `data-*` attributes are not boolean attributes -->
<p data-light={true}></p>
<p data-light={false}></p>

Astro v5.0 现在在渲染非布尔属性的 HTML 时保留完整的数据属性及其值:

¥Astro v5.0 now preserves the full data attribute with its value when rendering the HTML of non-boolean attributes:

<p allowfullscreen></p>
<p></p>
<p inherit="true"></p>
<p inherit></p>
<p inherit="false"></p>
<p data-light></p>
<p data-light="true"></p>
<p></p>
<p data-light="false"></p>

¥What should I do?

如果你依赖属性值(例如,定位元素或有条件地渲染),请更新你的代码以匹配新的非布尔属性值:

¥If you rely on attribute values, for example, to locate elements or to conditionally render, update your code to match the new non-boolean attribute values:

el.getAttribute('inherit') === ''
el.getAttribute('inherit') === 'false'
el.hasAttribute('data-light')
el.dataset.light === 'true'

改变:向 context.locals 添加值

标题部分 改变:向 context.locals 添加值

¥Changed: adding values to context.locals

在 Astro 4.x 中,在添加新值时,可以完全替换中间件、API 端点和页面中的整个 locals 对象。

¥In Astro 4.x, it was possible to completely replace the entire locals object in middleware, API endpoints, and pages when adding new values.

Astro 5.0 要求你将值附加到现有的 locals 对象而不删除它。中间件、API 端点和页面中的本地变量不再能被完全覆盖。

¥Astro 5.0 requires you to append values to the existing locals object without deleting it. Locals in middleware, API endpoints, and pages, can no longer be completely overridden.

¥What should I do?

以前你覆盖对象的地方,现在你必须为其分配值:

¥Where you previously were overwriting the object, you must now instead assign values to it:

src/middleware.js
ctx.locals = {
Object.assign(ctx.locals, {
one: 1,
two: 2
}
})

改变:params 不再解码

标题部分 改变:params 不再解码

¥Changed: params no longer decoded

在 Astro v4.x 中,传递给 getStaticPath()params 使用 decodeURIComponent 自动解码。

¥In Astro v4.x, params passed to getStaticPath() were automatically decoded using decodeURIComponent.

Astro v5.0 不再解码传递给 getStaticPathsparams 的值。如果需要,你必须自己手动解码它们。

¥Astro v5.0 no longer decodes the value of params passed to getStaticPaths. You must manually decode them yourself if needed.

¥What should I do?

如果你之前依赖自动解码,请在传递 params 时使用 decodeURI

¥If you were previously relying on the automatic decoding, use decodeURI when passing params.

src/pages/[id].astro
---
export function getStaticPaths() {
return [
{ params: { id: "%5Bpage%5D" } },
{ params: { id: decodeURI("%5Bpage%5D") } },
]
}
const { id } = Astro.params;
---

请注意,不鼓励对 getStaticPaths 使用 decodeURIComponent,因为它解码的字符比应解码的字符多,例如 /?# 等。

¥Note that the use of decodeURIComponent is discouraged for getStaticPaths because it decodes more characters than it should, for example /, ?, # and more.

改变:RouteData 类型被 IntegrationsRouteData 替换(集成 API)

标题部分 改变:RouteData 类型被 IntegrationsRouteData 替换(集成 API)

¥Changed: RouteData type replaced by IntegrationsRouteData (Integrations API)

在 Astro v4.x 中,astro:build:ssrastro:build:done 钩子内的 entryPoints 类型是 RouteData

¥In Astro v4.x, the entryPoints type inside the astro:build:ssr and astro:build:done hooks was RouteData.

Astro v5.0 中的 entryPoints 类型现在是 IntegrationRouteData,它包含 RouteData 类型的子集。字段 isIndexfallbackRoutes 已被删除。

¥Astro v5.0 the entryPoints type is now IntegrationRouteData, which contains a subset of the RouteData type. The fields isIndex and fallbackRoutes were removed.

¥What should I do?

更新你的适配器以将 entryPoints 的类型从 RouteData 更改为 IntegrationRouteData

¥Update your adapter to change the type of entryPoints from RouteData to IntegrationRouteData.

import type {RouteData} from 'astro';
import type {IntegrationRouteData} from "astro"
function useRoute(route: RouteData) {
function useRoute(route: IntegrationRouteData) {
}

改变:distURL 现在是一个数组(集成 API)

标题部分 改变:distURL 现在是一个数组(集成 API)

¥Changed: distURL is now an array (Integrations API)

在 Astro v4.x 中,RouteData.distURLundefinedURL

¥In Astro v4.x, RouteData.distURL was undefined or a URL.

Astro v5.0 将 IntegrationRouteData.distURL 的形状更新为 undefinedURL 数组。这修复了以前的错误,因为路由可以在磁盘上生成多个文件,尤其是在使用动态路由(如 [slug][...slug])时。

¥Astro v5.0 updates the shape of IntegrationRouteData.distURL to be undefined or an array of URLs. This fixes a previous error because a route can generate multiple files on disk, especially when using dynamic routes such as [slug] or [...slug].

¥What should I do?

更新你的代码以将 IntegrationRouteData.distURL 作为数组处理。

¥Update your code to handle IntegrationRouteData.distURL as an array.

if (route.distURL) {
if (route.distURL.endsWith('index.html')) {
// do something
}
for (const url of route.distURL) {
if (url.endsWith('index.html')) {
// do something
}
}
}

改变:传递给 app.render() 的参数(适配器 API)

标题部分 改变:传递给 app.render() 的参数(适配器 API)

¥Changed: Arguments passed to app.render() (Adapter API)

在 Astro 4.x 中,适配器 API 方法 app.render() 可以接收三个参数:必需的 request、选项对象或 routeData 对象和 locals

¥In Astro 4.x, The Adapter API method app.render() could receive three arguments: a mandatory request, an object of options or a routeData object, and locals.

Astro 5.0 将最后两个参数组合成一个名为 renderOptions 的选项参数。

¥Astro 5.0 combines these last two arguments into a single options argument named renderOptions.

¥What should I do?

将对象作为第二个参数传递给 app.render(),其中可以包括 routeDatalocals 作为属性。

¥Pass an object as the second argument to app.render(), which can include routeData and locals as properties.

const response = await app.render(request, routeData, locals);
const response = await app.render(request, {routeData, locals});

改变:supportedAstroFeatures 上的属性(适配器 API)

标题部分 改变:supportedAstroFeatures 上的属性(适配器 API)

¥Changed: Properties on supportedAstroFeatures (Adapter API)

在 Astro 4.x 中,supportedAstroFeatures 允许适配器作者指定其集成支持哪些功能,其中包含一个 assets 属性,用于指定支持 Astro 的哪些图片服务。

¥In Astro 4.x, supportedAstroFeatures, which allows adapter authors to specify which features their integration supports, included an assets property to specify which of Astro’s image services were supported.

Astro 5.0 用专用的 sharpImageService 属性替换此属性,用于确定适配器是否与内置的清晰图片服务兼容。

¥Astro 5.0 replaces this property with a dedicated sharpImageService property, used to determine whether the adapter is compatible with the built-in sharp image service.

v5.0 还为适配器的 supportedAstroFeatures 的不同属性添加了一个新的 limited 值,这表明适配器与该功能兼容,但有一些限制。这对于支持某项功能的适配器很有用,但并非在所有情况下或所有选项下都适用。

¥v5.0 also adds a new limited value for the different properties of supportedAstroFeatures for adapters, which indicates that the adapter is compatible with the feature, but with some limitations. This is useful for adapters that support a feature, but not in all cases or with all options.

此外,适配器的 supportedAstroFeatures 上不同属性的值现在可以是对象,具有 supportmessage 属性。当适配器与某个功能不兼容时,message 属性的内容将在 Astro CLI 中显示一条有用的消息。这对于新的 limited 值特别有用,可以向用户解释为什么支持有限。

¥Additionally, the value of the different properties on supportedAstroFeatures for adapters can now be objects, with support and message properties. The content of the message property will show a helpful message in the Astro CLI when the adapter is not compatible with a feature. This is notably useful with the new limited value, to explain to the user why support is limited.

¥What should I do?

如果你使用 assets 属性,请将其删除,因为它不再可用。要指定你的适配器支持内置的 Sharp 图片服务,请将其替换为 sharpImageService

¥If you were using the assets property, remove this as it is no longer available. To specify that your adapter supports the built-in sharp image service, replace this with sharpImageService.

你可能还希望使用新的 limited 选项更新你支持的功能,并包含有关你的适配器支持的消息。

¥You may also wish to update your supported features with the new limited option and include a message about your adapter’s support.

my-adapter.mjs
supportedAstroFeatures: {
assets: {
supportKind: "stable",
isSharpCompatible: true,
isSquooshCompatible: true,
},
sharpImageService: {
support: "limited",
message: 'This adapter supports the built-in sharp image service, but with some limitations.'
}
}

已删除:已弃用的开发工具栏应用定义形状(开发工具栏 API)

标题部分 已删除:已弃用的开发工具栏应用定义形状(开发工具栏 API)

¥Removed: Deprecated definition shape for dev toolbar apps (Dev Toolbar API)

在 Astro 4.x 中,构建开发工具栏应用时,仍然可以使用以前弃用的 addDevToolbarApp(string); 签名。然后,通过应用的 entrypoint 的默认导出,可以使用 idtitleicon 属性来定义应用。

¥In Astro 4.x, when building a dev toolbar app, it was still possible to use the previously deprecated addDevToolbarApp(string); signature. The id, title, and icon properties to define the app were then made available through the default export of the app’s entrypoint.

Astro 5.0 在定义开发工具栏应用时完全删除此选项,转而使用当前对象形状,这种集成更加直观,并允许 Astro 在工具栏应用无法正确加载时提供更好的错误。

¥Astro 5.0 completely removes this option entirely in favor of the current object shape when defining a dev toolbar app in an integration that’s more intuitive and allows Astro to provide better errors when toolbar apps fail to load correctly.

¥What should I do?

如果你使用的是已弃用的形状,请更新你的开发工具栏应用以使用新形状:

¥If you were using the deprecated shape, update your dev toolbar app to use the new shape:

my-integration.mjs
// Old shape
addDevToolbarApp("./my-app.js");
// New shape
addDevToolbarApp({
id: "my-app",
name: "My App",
icon: "<svg>...</svg>",
entrypoint: "./my-app.js",
});
my-dev-toolbar-app.mjs
export default {
id: 'my-dev-toolbar-app',
title: 'My Dev Toolbar App',
icon: '🚀',
init() {
// ...
}
}

已删除:在 create-astro 期间配置 Typescript

标题部分 已删除:在 create-astro 期间配置 Typescript

¥Removed: configuring Typescript during create-astro

在 Astro v4.x 中,在使用 create astro 创建新项目时,可以通过回答问题或传递具有所需 TypeScript 设置的关联 --typescript 标志来在 Astro 的三种 TypeScript 设置之间进行选择。

¥In Astro v4.x, it was possible to choose between Astro’s three TypeScript settings when creating a new project using create astro, either by answering a question or by passing an associated --typescript flag with the desired TypeScript setting.

Astro 5.0 更新了 create astro CLI 命令以删除 TypeScript 问题及其关联的 --typescript 标志。“strict” 预设现在是使用命令行创建的所有新项目的默认预设,并且当时不再可能对其进行自定义。但是,仍然可以在 tsconfig.json 中手动更改 TypeScript 模板。

¥Astro 5.0 updates the create astro CLI command to remove the TypeScript question and its associated --typescript flag. The “strict” preset is now the default for all new projects created with the command line and it is no longer possible to customize this at that time. However, the TypeScript template can still be changed manually in tsconfig.json.

¥What should I do?

如果你将 --typescript 标志与 create-astro 一起使用,请将其从命令中删除。

¥If you were using the --typescript flag with create-astro, remove it from your command.

终端窗口
npm create astro@latest -- --template <example-name> --typescript strict
npm create astro@latest -- --template <example-name>

¥Community Resources

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

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

¥Known Issues

请检查 GitHub 上的 Astro 问题 是否有任何报告的问题,或自行提交问题。

¥Please check Astro’s issues on GitHub for any reported issues, or to file an issue yourself.

Astro 中文网 - 粤ICP备13048890号