Skip to content

旧版 v0.x 升级指南

本指南将帮助你通过 Astro v1 之前版本中的重大更改进行升级。

¥This guide will help you upgrade through breaking changes in pre-v1 versions of Astro.

你可以使用包管理器将项目的 Astro 版本更新到最新版本。如果你使用 Astro 集成,你还需要将其更新到最新版本。

¥You can update your project’s version of Astro to the latest version using your package manager. If you’re using Astro integrations, you’ll also want to update those to the latest version.

Terminal window
# updates the astro dependency:
npm upgrade astro
# or, to update all dependencies:
npm upgrade

请阅读下面的指南,了解主要亮点以及有关如何处理重大变更的说明。

¥Read the guide below for major highlights and instructions on how to handle breaking changes.

Astro v1.0 引入了一些更改,你在从 v0.x 和 v1.0-beta 版本迁移时应注意这些更改。请参阅下面的更多细节。

¥Astro v1.0 introduces some changes that you should be aware of when migrating from v0.x and v1.0-beta releases. See below for more details.

¥Updated: Vite 3

Astro v1.0 已从 Vite 2 升级到 Vite 3。我们已经在 Astro 内为你处理了大部分升级;然而,一些微妙的 Vite 行为在不同版本之间仍可能会发生变化。如果遇到问题请参考官方的 Vite 迁移指南

¥Astro v1.0 has upgraded from Vite 2 to Vite 3. We’ve handled most of the upgrade for you inside of Astro; however, some subtle Vite behaviors may still change between versions. Refer to the official Vite Migration Guide if you run into trouble.

已弃用:Astro.canonicalURL

Section titled 已弃用:Astro.canonicalURL

¥Deprecated: Astro.canonicalURL

你现在可以使用新的 Astro.url 辅助程序从当前页面/请求 URL 构建你自己的规范 URL。

¥You can now use the new Astro.url helper to construct your own canonical URL from the current page/request URL.

// Before:
const canonicalURL = Astro.canonicalURL;
// After:
const canonicalURL = new URL(Astro.url.pathname, Astro.site);

¥Changed: Scoped CSS specificity

特异性 现在将保留在作用域 CSS 样式中。此更改将导致大多数作用域样式碰巧优先于全局样式。但是,这种行为不再得到明确保证。

¥Specificity will now be preserved in scoped CSS styles. This change will cause most scoped styles to happen to take precedence over global styles. But, this behavior is no longer explicitly guaranteed.

从技术上讲,这是使用 :where() 伪类 完成的,而不是直接在 Astro 的 CSS 输出中使用类。

¥Technically, this is accomplished using the :where() pseudo-class instead of using classes directly in Astro’s CSS output.

我们以 Astro 组件中的以下样式块为例:

¥Let’s use the following style block in an Astro component as an example:

<style>
div { color: red; } /* 0-0-1 specificity */
</style>

以前,Astro 会将其转换为以下 CSS,其特异性为 0-1-1 - 比源 CSS 更高:

¥Previously, Astro would transform this into the following CSS, which has a specificity of 0-1-1 — a higher specificity than the source CSS:

div.astro-XXXXXX { color: red; } /* 0-1-1 specificity */

现在,Astro 用 :where() 封装类选择器,保持编写的特异性:

¥Now, Astro wraps the class selector with :where(), maintaining the authored specificity:

div:where(.astro-XXXXXX) { color: red; } /* 0-0-1 specificity */

之前的特异性增加使得将 Astro 中的范围样式与其他 CSS 文件或样式库(例如 Tailwind、CSS 模块、样式组件、Stitches)相结合变得困难。这一更改将使 Astro 的作用域样式能够与它们一致地工作,同时仍然保留防止样式在组件外部应用的排他边界。

¥The previous specificity increase made it hard to combine scoped styles in Astro with other CSS files or styling libraries (e.g. Tailwind, CSS Modules, Styled Components, Stitches). This change will allow Astro’s scoped styles to work consistently alongside them while still preserving the exclusive boundaries that prevent styles from applying outside the component.

已弃用:Markdown 中的组件和 JSX

Section titled 已弃用:Markdown 中的组件和 JSX

¥Deprecated: Components and JSX in Markdown

Astro 默认不再支持 Markdown 页面中的组件或 JSX 表达式。为了获得长期支持,你应该迁移到 @astrojs/mdx 集成。

¥Astro no longer supports components or JSX expressions in Markdown pages by default. For long-term support you should migrate to the @astrojs/mdx integration.

为了使迁移更容易,可以使用新的 legacy.astroFlavoredMarkdown 标志(在 v2.0 中删除)来重新启用以前的 Markdown 功能。

¥To make migrating easier, a new legacy.astroFlavoredMarkdown flag (removed in v2.0) can be used to re-enable previous Markdown features.

将现有 .md 文件转换为 .mdx

Section titled 将现有 .md 文件转换为 .mdx

¥Converting existing .md files to .mdx

如果你不熟悉 MDX,可以按照以下一些步骤将现有 “Astro 风味 Markdown” 文件快速转换为 MDX。当你了解有关 MDX 的更多信息时,请随意探索编写页面的其他方法!

¥If you’re not familiar with MDX, here are some steps you can follow to quickly convert an existing “Astro Flavored Markdown” file to MDX. As you learn more about MDX, feel free to explore other ways of writing your pages!

  1. Install the @astrojs/mdx integration.

  2. Change your existing .md file extensions to .mdx

  3. Remove any setup: properties from your frontmatter, and write any import statements below the frontmatter instead.

    src/pages/posts/my-post.mdx
    ---
    layout: '../../layouts/BaseLayout.astro'
    setup: |
    import ReactCounter from '../../components/ReactCounter.jsx'
    title: 'Migrating to MDX'
    date: 2022-07-26
    tags: ["markdown", "mdx", "astro"]
    ---
    import ReactCounter from '../../components/ReactCounter.jsx'
    # {frontmatter.title}
    Here is my counter component, working in MDX:
    <ReactCounter client:load />
  4. Update any Astro.glob() statements that currently return .md files so that they will now return your .mdx files.

  5. Update any use of the <Content /> component to use the default export when importing MDX:

    src/pages/index.astro
    ---
    // Multiple imports with Astro.glob
    const mdxPosts = await Astro.glob('./posts/*.mdx');
    ---
    {mdxPosts.map(Post => <Post.default />)}
    src/pages/index.astro
    ---
    // Import a single page
    import { default as About } from './about.mdx';
    ---
    <About />

¥<Markdown /> Component Removed

Astro 的内置 <Markdown /> 组件已移至单独的包中。要继续使用此组件,你现在需要安装 @astrojs/markdown-component 并相应地更新你的导入。详细信息请参见 @astrojs/markdown 自述文件

¥Astro’s built-in <Markdown /> component has been moved to a separate package. To continue using this component, you will now need to install @astrojs/markdown-component and update your imports accordingly. For more details, see the @astrojs/markdown README.

¥Migrate to v1.0.0-beta

2022 年 4 月 4 日,我们发布了 Astro 1.0 Beta!🎉

¥On April 4, 2022 we released the Astro 1.0 Beta! 🎉

如果你来自 v0.25 或更早版本,请确保你已阅读并遵循下面的 v0.26 迁移指南,其中包含几项重大重大更改。

¥If you are coming from v0.25 or earlier, make sure you have read and followed the v0.26 Migration Guide below, which contained several major breaking changes.

Astro 的 v1.0.0-beta.0 版本不包含重大更改。以下是测试期间引入的小变化。

¥The v1.0.0-beta.0 release of Astro contained no breaking changes. Below are small changes that were introduced during the beta period.

¥Changed: RSS Feeds

现在应该使用 @astrojs/rss 包生成 RSS 提要,如 RSS 指南 中所述。

¥RSS feeds should now be generated using the @astrojs/rss package, as described in our RSS guide.

¥Migrate to v0.26

¥New Configuration API

我们的配置 API 已经过重新设计,以解决去年出现的一些明显的混乱点。大多数配置选项刚刚被移动或重命名,这对于大多数用户来说有望是一个快速更新。一些选项已进行了更大幅度的重构,并且可能需要一些额外的更改:

¥Our Configuration API has been redesigned to solve a few glaring points of confusion that had built up over the last year. Most of the configuration options have just been moved or renamed, which will hopefully be a quick update for most users. A few options have been refactored more heavily, and may require a few additional changes:

  • .buildOptions.site 已替换为 .site(你部署的域)和新的 .base(你部署的子路径)选项。

  • .markdownOptions 已替换为 .markdown,这是一个基本相似的配置对象,但进行了一些小更改以简化 Markdown 配置。

  • .sitemap 已移至 @astrojs/sitemap 集成中。

如果你使用旧配置运行 Astro,你将看到一条警告,其中包含有关如何更新的说明。有关升级的更多信息,请参阅我们更新的 配置参考

¥If you run Astro with legacy configuration, you will see a warning with instructions on how to update. See our updated Configuration Reference for more information on upgrading.

请阅读 RFC0019 了解有关这些更改的更多背景信息。

¥Read RFC0019 for more background on these changes.

¥New Markdown API

Astro v0.26 为你的内容发布了全新的 Markdown API。这包括三个面向用户的主要变化:

¥Astro v0.26 releases a brand new Markdown API for your content. This included three major user-facing changes:

  • 你现在可以直接使用 ESM 导入来处理 import/import() markdown 内容。

  • 新的 Astro.glob() API,更容易进行全局导入(尤其是 Markdown)。

  • 重大变化:Astro.fetchContent() 已被删除并替换为 Astro.glob()

  • 重大变化:Markdown 对象具有更新的界面。

// v0.25
let allPosts = Astro.fetchContent('./posts/*.md');
// v0.26+
let allPosts = await Astro.glob('./posts/*.md');

迁移时,请注意新的 Markdown 对象接口。例如,Frontmatter 已移至 .frontmatter 属性,因此 post.title 等引用应更改为 post.frontmatter.title

¥When migrating, be careful about the new Markdown object interface. Frontmatter, for example, has been moved to the .frontmatter property, so references like post.title should change to post.frontmatter.title.

这应该可以为 Markdown 用户解决许多问题,包括为大型网站带来一些不错的性能提升。

¥This should solve many issues for Markdown users, including some nice performance boosts for larger sites.

请阅读 RFC0017 了解有关这些更改的更多背景信息。

¥Read RFC0017 for more background on these changes.

¥New Default Script Behavior

Astro 组件中的 <script> 标签现在默认构建、打包和优化。这完成了一项长期举措,使我们的 Astro 组件语法更加一致,与我们今天的 <style> 标签的默认优化行为相匹配。

¥<script> tags in Astro components are now built, bundled and optimized by default. This completes a long-term move to make our Astro component syntax more consistent, matching the default-optimized behavior our <style> tags have today.

这包括一些需要注意的变化:

¥This includes a few changes to be aware of:

  • 打破:<script hoist> 是新的默认 <script> 行为。hoist 属性已被删除。要使用新的默认行为,请确保 <script> 标记上没有其他属性。例如,如果你以前使用过 type="module",请将其删除。

  • 新的 <script is:inline> 指令,将 <script> 标签恢复为以前的默认行为(未构建、解绑、未受 Astro 影响)。

  • 新的 <style is:inline> 指令,在页面模板中保留内联样式标记(类似于之前的 <script> 行为)。

  • 新的 <style is:global> 指令将在未来版本中取代 <style global>

// v0.25
<script hoist type="module">
// v0.26+
<script>

有关完整详细信息,请参阅如何在 Astro 中使用 客户端脚本

¥See how to use client-side scripts in Astro for full details.

请阅读 RFC0016 了解有关这些更改的更多背景信息。

¥Read RFC0016 for more background on these changes.

¥Updated Astro.request API

Astro.request 已从我们的自定义对象更改为标准 Request 对象。这是使用更多 Web 标准 API 的项目的一部分,特别是在 SSR 方面。

¥Astro.request has been changed from our custom object to a standard Request object. This is part of a project to use more web standard APIs, especially where SSR is concerned.

这包括一些需要注意的变化:

¥This includes a few changes to be aware of:

  • Astro.request 更改为 要求 对象。

  • Astro.request.params 移至 Astro.params

  • Astro.request.canonicalURL 移至 Astro.canonicalURL

请阅读 RFC0018 了解有关这些更改的更多背景信息。

¥Read RFC0018 for more background on these changes.

¥Other Changes

  • 改进 Astro.slots API 以支持将参数传递给基于函数的槽。这允许更符合人机工程学的实用程序组件接受回调函数作为子函数。

  • 更新 CLI 输出格式,尤其是错误报告方面的格式。

  • 更新 @astrojs/compiler,修复一些与 frontmatter 中 RegExp 使用相关的 bug

¥Migrate to v0.25

¥Astro Integrations

renderers 配置已被新的官方集成系统取代!这为 Astro 解锁了一些非常令人兴奋的新功能。你可以阅读我们的 使用集成 指南,了解有关如何使用这个新系统的更多详细信息。

¥The renderers config has been replaced by a new, official integration system! This unlocks some really exciting new features for Astro. You can read our Using Integrations guide for more details on how to use this new system.

集成取代了我们最初的 renderers 概念,并为现有用户带来了一些重大更改和新的默认设置。下面介绍了这些更改。

¥Integrations replace our original renderers concept, and come with a few breaking changes and new defaults for existing users. These changes are covered below.

已删除:内置框架支持

Section titled 已删除:内置框架支持

¥Removed: Built-in Framework Support

此前,React、Preact、Svelte 和 Vue 都默认包含在 Astro 中。从 v0.25.0 开始,Astro 不再附带任何内置渲染器。如果你还没有为你的项目定义 renderers 配置条目,那么你现在需要自己安装这些框架。

¥Previously, React, Preact, Svelte, and Vue were all included with Astro by default. Starting in v0.25.0, Astro no longer comes with any built-in renderers. If you did not have a renderers configuration entry already defined for your project, you will now need to install those frameworks yourself.

阅读我们的 逐步演练,了解如何为你当前使用的框架添加新的 Astro 集成。

¥Read our step-by-step walkthrough to learn how to add a new Astro integration for the framework(s) that you currently use.

¥Deprecated: Renderers

新的集成系统取代了之前的 renderers 系统,包括 npm 上发布的 @astrojs/renderer-* 包。接下来,@astrojs/renderer-react 变为 @astrojs/react@astrojs/renderer-vue 变为 @astrojs/vue,依此类推。

¥The new integration system replaces the previous renderers system, including the published @astrojs/renderer-* packages on npm. Going forward, @astrojs/renderer-react becomes @astrojs/react, @astrojs/renderer-vue becomes @astrojs/vue, and so on.

迁移:将 Astro 更新为 v0.25.0,然后使用包含过时 "renderers" 配置的旧配置文件运行 astro devastro build。你将立即看到一条通知,告诉你根据当前配置需要对 astro.config.mjs 文件进行的具体更改。你还可以使用下表自行更新你的软件包。

¥To migrate: update Astro to v0.25.0 and then run astro dev or astro build with your old configuration file containing the outdated "renderers" config. You will immediately see a notice telling you the exact changes you need to make to your astro.config.mjs file, based on your current config. You can also update your packages yourself, using the table below.

如需更深入的演练,请阅读我们的 分步指南,了解如何使用新的 Astro 框架集成替换现有渲染器。

¥For a deeper walkthrough, read our step-by-step guide to learn how to replace existing renderers with a new Astro framework integration.

Terminal window
# Install your new integrations and frameworks:
# (Read the full walkthrough: https://astro.nodejs.cn/en/guides/integrations-guide)
npm install @astrojs/lit lit
npm install @astrojs/react react react-dom
// Then, update your `astro.config.mjs` file:
// (Read the full walkthrough: https://astro.nodejs.cn/en/guides/integrations-guide)
import lit from '@astrojs/lit';
import react from '@astrojs/react';
export default {
renderers: ['@astrojs/renderer-lit', '@astrojs/renderer-react'],
integrations: [lit(), react()],
}
npm 上已弃用的渲染器v0.25+ 在 npm 上的集成
@astrojs/renderer-react@astrojs/react
@astrojs/renderer-preact@astrojs/preact
@astrojs/renderer-solid@astrojs/solid-js
@astrojs/renderer-vue@astrojs/vue
@astrojs/renderer-svelte@astrojs/svelte

¥Handling Peer Dependencies

与旧的渲染器不同,集成不再将框架本身(“react”、“svelte”、“vue” 等)标记为集成的直接依赖。相反,除了集成之外,你现在还应该安装框架包。

¥Unlike the old renderers, integrations no longer mark the frameworks themselves (“react”, “svelte”, “vue”, etc.) as direct dependencies of the integration. Instead, you should now install your framework packages in addition to your integrations.

Terminal window
# Example: Install integrations and frameworks together
npm install @astrojs/react react react-dom

如果你在启动 Astro 时看到 "Cannot find package 'react'"(或类似)警告,则意味着你需要将该软件包安装到你的项目中。有关详细信息,请参阅故障排除指南中的 注意对等依赖

¥If you see a "Cannot find package 'react'" (or similar) warning when you start up Astro, that means that you need to install that package into your project. See our note on peer dependencies in the troubleshooting guide for more information.

如果你使用的是 npm 和 Node v16+,那么 npm 可能会自动为你处理,因为最新版本的 npm (v7+) 会自动为你安装这样的对等依赖。在这种情况下,将 “react” 这样的框架安装到你的项目中是可选的,但仍然是推荐的步骤。

¥If you are using npm & Node v16+, then this may be automatically handled for you by npm, since the latest version of npm (v7+) installs peer dependencies like this for you automatically. In that case, installing a framework like “react” into your project is an optional but still recommended step.

¥Updated: Syntax Highlighting

我们喜欢找到 “只是工作” 开箱即用的合理默认值。作为其中的一部分,我们决定将 志木 作为新的默认语法荧光笔。它预先配置了 github-dark 主题,在代码块中提供零配置高亮,无需无关的 CSS 类、样式表或客户端 JS。

¥We love to find sensible defaults that “just work” out-of-the-box. As part of this, we decided to make Shiki our new default syntax highlighter. This comes pre-configured with the github-dark theme, providing zero-config highlighting in your code blocks without extraneous CSS classes, stylesheets, or client-side JS.

查看我们的新款 语法高亮文档 了解完整详细信息。如果你希望将 Prism 保留为语法高亮器,请在项目的 markdown 配置中使用 syntaxHighlight 选项设置为 'prism'

¥Check our new syntax highlighting docs for full details. If you prefer to keep Prism as your syntax highlighter, set the syntaxHighlight option to 'prism' in your project’s markdown configuration.

¥The <Prism /> component has a new home

作为我们尽可能保持 Astro core 精简的使命的一部分,我们已将内置 Prism 组件从 astro/components 中移出并移至 @astrojs/prism 包中。你现在可以从 @astrojs/prism 导入此组件,如下所示:

¥As part of our mission to keep Astro core as lean as possible, we’ve moved the built-in Prism component out of astro/components and into the @astrojs/prism package. You can now import this component from @astrojs/prism like so:

---
import { Prism } from '@astrojs/prism';
---

由于 @astrojs/prism 软件包仍然与 astro 核心打包在一起,因此你不需要安装任何新内容,也不需要添加 Prism 作为集成!但是,请注意,我们确实计划将来将 @astrojs/prism(以及一般的 Prism 语法高亮)提取到单独的可安装包中。详细信息请参见 <Prism /> 组件 API 参考

¥Since the @astrojs/prism package is still bundled with astro core, you won’t need to install anything new, nor add Prism as an integration! However, note that we do plan to extract @astrojs/prism (and Prism syntax highlighting in general) to a separate, installable package in the future. See the <Prism /> component API reference for more details.

¥CSS Parser Upgrade

我们的内部 CSS 解析器已更新,并且更好地支持高级 CSS 语法,例如容器查询。对于大多数用户来说,这应该是一个几乎看不见的变化,但希望高级用户能够享受新的 CSS 功能支持。

¥Our internal CSS parser has been updated, and comes with better support for advanced CSS syntax, like container queries. This should be a mostly invisible change for most users, but hopefully advanced users will enjoy the new CSS feature support.

¥Migrate to v0.24

0.24 引入了一种新的静态构建策略,它改变了一些功能的行为。在 Astro 的早期版本中,这是带有选择加入标志的可用行为:--experimental-static-build

¥0.24 introduced a new static build strategy that changes the behavior of a few features. In previous versions of Astro this was available behavior with an opt-in flag: --experimental-static-build.

要进行迁移,请注意迁移到此新构建引擎所需的以下更改。你可以随时对代码库进行这些更改,以便提前做好准备。

¥To migrate for the transition, be aware of the following changes that will be required to move to this new build engine. You can make these changes to your codebase at any time so that you are ready ahead of schedule.

¥Deprecated: Astro.resolve()

Astro.resolve() 允许你获取你可能想要在浏览器中引用的资源的已解析 URL。这最常用于 <link><img> 标签内,以根据需要加载 CSS 文件和图片。不幸的是,这将不再有效,因为 Astro 现在是在构建时而不是渲染时构建资源。你需要将资源参考升级为以下可用的面向未来的选项之一:

¥Astro.resolve() allows you to get resolved URLs to assets that you might want to reference in the browser. This was most commonly used inside of <link> and <img> tags to load CSS files and images as needed. Unfortunately, this will no longer work due to Astro now building assets at build time rather than at render time. You’ll want to upgrade your asset references to one of the following future-proof options available going forward:

¥How to Resolve CSS Files

1.

示例:import './style.css'; 何时使用这个:如果你的 CSS 文件位于 src/ 目录中,并且你想要自动 CSS 构建和优化功能。

¥Example: import './style.css'; When to use this: If your CSS file lives inside of the src/ directory, and you want automatic CSS build and optimization features.

使用 ESM 导入将一些 CSS 添加到页面上。Astro 检测这些 CSS 导入,然后自动构建、优化 CSS 并将其添加到页面。这是从 Astro.resolve() 迁移的最简单方法,同时保留 Astro 提供的自动构建/打包功能。

¥Use an ESM import to add some CSS onto the page. Astro detects these CSS imports and then builds, optimizes, and adds the CSS to the page automatically. This is the easiest way to migrate from Astro.resolve() while keeping the automatic building/bundling that Astro provides.

---
// Example: Astro will include and optimize this CSS for you automatically
import './style.css';
---
<html><!-- Your page here --></html>

导入 CSS 文件应该可以在支持 ESM 导入的任何地方使用,包括:

¥Importing CSS files should work anywhere that ESM imports are supported, including:

  • JavaScript 文件

  • TypeScript 文件

  • Astro 组件 frontmatter

  • 非 Astro 组件,例如 React、Svelte 等

使用此方法导入 CSS 文件时,任何 @import 语句也会被解析并内联到导入的 CSS 文件中。所有 url() 引用也相对于源文件进行解析,任何 url() 引用的资源都将包含在最终版本中。

¥When a CSS file is imported using this method, any @import statements are also resolved and inlined into the imported CSS file. All url() references are also resolved relative to the source file, and any url() referenced assets will be included in the final build.

2.

示例:<link href="/style.css"> 何时使用这个:如果你的 CSS 文件位于 public/ 内,并且你更喜欢自己创建 HTML link 元素。

¥Example: <link href="/style.css"> When to use this: If your CSS file lives inside of public/, and you prefer to create your HTML link element yourself.

你可以通过组件模板中的绝对 URL 路径引用 public/ 目录内的任何文件。如果你想自己控制页面上的 <link> 标记,这是一个不错的选择。但是,当你使用上述 import 方法时,此方法还会跳过 Astro 提供的 CSS 处理、打包和优化。

¥You can reference any file inside of the public/ directory by absolute URL path in your component template. This is a good option if you want to control the <link> tag on the page yourself. However, this approach also skips the CSS processing, bundling and optimizations that are provided by Astro when you use the import method described above.

我们建议使用 import 方法而不是绝对 URL 方法,因为它默认提供最佳的 CSS 性能和功能。

¥We recommend using the import approach over the absolute URL approach since it provides the best possible CSS performance and features by default.

如何解析 JavaScript 文件

Section titled 如何解析 JavaScript 文件

¥How to Resolve JavaScript Files

1.

示例:<script src="/some-external-script.js" /> 何时使用这个:如果你的 JavaScript 文件位于 public/ 内。

¥Example: <script src="/some-external-script.js" /> When to use this: If your JavaScript file lives inside of public/.

你可以通过 Astro 组件模板中的绝对 URL 路径引用 public/ 目录内的任何文件。对于外部脚本来说,这是一个很好的默认选项,因为它允许你自己控制页面上的 <script> 标记。

¥You can reference any file inside of the public/ directory by absolute URL path in your Astro component templates. This is a good default option for external scripts because it lets you control the <script> tag on the page yourself.

请注意,当你使用下面描述的 import 方法时,此方法会跳过 Astro 提供的 JavaScript 处理、打包和优化。然而,对于已经与 Astro 分开发布和缩小的任何外部脚本来说,这可能是首选。如果你的脚本是从外部源下载的,那么此方法可能是首选。

¥Note that this approach skips the JavaScript processing, bundling and optimizations that are provided by Astro when you use the import method described below. However, this may be preferred for any external scripts that have already been published and minified separately from Astro. If your script was downloaded from an external source, then this method is probably preferred.

2.

示例:<script hoist>import './some-external-script.js';</script> 何时使用这个:如果你的外部脚本位于 src/ 内并且它支持 ESM 模块类型。

¥Example: <script hoist>import './some-external-script.js';</script> When to use this: If your external script lives inside of src/ and it supports the ESM module type.

在 Astro 模板中的 <script hoist> 元素内使用 ESM 导入,Astro 将在最终构建中包含 JavaScript 文件。Astro 检测这些 JavaScript 客户端导入,然后自动构建、优化 JavaScript 并将其添加到页面。这是从 Astro.resolve() 迁移的最简单方法,同时保留 Astro 提供的自动构建/打包功能。

¥Use an ESM import inside of a <script hoist> element in your Astro template, and Astro will include the JavaScript file in your final build. Astro detects these JavaScript client-side imports and then builds, optimizes, and adds the JavaScript to the page automatically. This is the easiest way to migrate from Astro.resolve() while keeping the automatic building/bundling that Astro provides.

<script hoist>
import './some-external-script.js';
</script>

请注意,Astro 会将此外部脚本与客户端 JavaScript 的其余部分打包在一起,并将其加载到 type="module" 脚本上下文中。一些较旧的 JavaScript 文件可能不是为 module 上下文编写的,在这种情况下,可能需要更新它们才能使用此方法。

¥Note that Astro will bundle this external script with the rest of your client-side JavaScript, and load it in the type="module" script context. Some older JavaScript files may not be written for the module context, in which case they may need to be updated to use this method.

如何解析图片和其他资源

Section titled 如何解析图片和其他资源

¥How to Resolve Images & Other Assets

1.

示例:<img src="/penguin.png"> 何时使用这个:如果你的资源位于 public/ 内。

¥Example: <img src="/penguin.png"> When to use this: If your asset lives inside of public/.

如果你将图片放置在 public/ 内,你可以直接在组件模板中通过绝对 URL 路径安全地引用它们。这是引用当前可以使用的资源的最简单方法,建议大多数刚开始使用 Astro 的用户使用。

¥If you place your images inside of public/ you can safely reference them by absolute URL path directly in your component templates. This is the simplest way to reference an asset that you can use today, and it is recommended for most users who are getting started with Astro.

2.

示例:import imgUrl from './penguin.png' 何时使用这个:如果你的资源位于 src/ 目录中,并且你想要自动优化功能,如文件名散列。

¥Example: import imgUrl from './penguin.png' When to use this: If your asset lives inside of the src/ directory, and you want automatic optimization features like filename hashing.

这可以在任何 JavaScript 或 Astro 组件内部工作,并返回最终图片的解析 URL。获得解析后的 URL 后,你可以在组件模板内的任何位置使用它。

¥This works inside of any JavaScript or Astro component, and returns a resolved URL to the final image. Once you have the resolved URL, you can use it anywhere inside of the component template.

---
// Example: Astro will include this image file in your final build
import imgUrl from './penguin.png';
---
<img src={imgUrl} />

与 Astro 处理 CSS 的方式类似,ESM 导入允许 Astro 自动为你执行一些简单的构建优化。例如,使用 ESM 导入(例如:import imgUrl from './penguin.png')导入的 src/ 内的任何资源都将自动对其文件名进行哈希处理。这可以让你在服务器上更积极地缓存文件,从而提高用户性能。未来,Astro 可能会添加更多这样的优化。

¥Similar to how Astro handles CSS, the ESM import allows Astro to perform some simple build optimizations for you automatically. For example, any asset inside of src/ that is imported using an ESM import (ex: import imgUrl from './penguin.png') will have its filename hashed automatically. This can let you cache the file more aggressively on the server, improving user performance. In the future, Astro may add more optimizations like this.

提示:如果你不喜欢静态 ESM 导入,Astro 还支持动态 ESM 导入。仅当你喜欢此语法时,我们才推荐此选项:<img src={(await import('./penguin.png')).default} />

¥Tip: If you dislike static ESM imports, Astro also supports dynamic ESM imports. We only recommend this option if you prefer this syntax: <img src={(await import('./penguin.png')).default} />.

¥Deprecated: <script> Default Processing

以前,所有 <script> 元素都是从最终的 HTML 输出中读取并自动处理和打包。此行为不再是默认行为。从 0.24 开始,你必须通过 hoist 属性选择加入 <script> 元素处理。提升模块也需要 type="module"

¥Previously, all <script> elements were read from the final HTML output and processed + bundled automatically. This behavior is no longer the default. Starting in 0.24, you must opt-in to <script> element processing via the hoist attribute. The type="module" is also required for hoisted modules.

<script>
// Will be rendered into the HTML exactly as written!
// ESM imports will not be resolved relative to the file.
</script>
<script type="module" hoist>
// Processed! Bundled! ESM imports work, even to npm packages.
</script>

¥Migrate to v0.23

¥Missing Sass Error

Preprocessor dependency "sass" not found. Did you install it?

为了减少 npm 安装大小,我们已将 Sass 移出为可选依赖。如果你在项目中使用 Sass,你需要确保运行 npm install sass --save-dev 以将其保存为依赖。

¥In our quest to reduce npm install size, we’ve moved Sass out to an optional dependency. If you use Sass in your project, you’ll want to make sure that you run npm install sass --save-dev to save it as a dependency.

¥Deprecated: Unescaped HTML

在 Astro v0.23+ 中,表达式中未转义的 HTML 内容现已弃用。在未来的版本中,表达式中的内容将对字符串进行转义,以防止意外的 HTML 注入。

¥In Astro v0.23+, unescaped HTML content in expressions is now deprecated. In future releases, content within expressions will have strings escaped to protect against unintended HTML injection.

<h1>{title}</h1> <!-- <h1>Hello <strong>World</strong></h1> -->
<h1>{title}</h1> <!-- <h1>Hello &lt;strong&gt;World&lt;/strong&gt;</h1> -->

要继续注入未转义的 HTML,你现在可以使用 set:html

¥To continue injecting unescaped HTML, you can now use set:html.

<h1>{title}</h1>
<h1 set:html={title} />

为了避免封装元素,set:html 可以与 <Fragment> 一起使用。

¥To avoid a wrapper element, set:html can work alongside <Fragment>.

<h1>{title}!</h1>
<h1><Fragment set:html={title}>!</h1>

你还可以使用 set:text 防止意外的 HTML 注入。

¥You can also protect against unintended HTML injection with set:text.

<h1 set:text={title} /> <!-- <h1>Hello &lt;strong&gt;World&lt;/strong&gt;</h1> -->

¥Migrate to v0.21

从 v0.21 开始,Astro 是使用 Vite 构建的。因此,snowpack.config.mjs 中写入的配置应移至 astro.config.mjs 中。

¥Starting in v0.21, Astro is built with Vite. As a result, configurations written in snowpack.config.mjs should be moved into astro.config.mjs.

// @ts-check
/** @type {import('astro').AstroUserConfig} */
export default {
renderers: [],
vite: {
plugins: [],
},
};

要了解有关配置 Vite 的更多信息,请访问他们的 配置指南

¥To learn more about configuring Vite, please visit their configuration guide.

¥Vite Plugins

在 Astro v0.21+ 中,Vite 插件可以在 astro.config.mjs 内配置。

¥In Astro v0.21+, Vite plugins may be configured within astro.config.mjs.

import { imagetools } from 'vite-imagetools';
export default {
vite: {
plugins: [imagetools()],
},
};

要了解有关 Vite 插件的更多信息,请访问他们的 插件指南

¥To learn more about Vite plugins, please visit their plugin guide.

¥Vite Changes to Renderers

在 Astro v0.21+ 中,插件现在应该使用 viteConfig()

¥In Astro v0.21+, plugins should now use viteConfig().

renderer-svelte/index.js
import { svelte } from '@sveltejs/vite-plugin-svelte';
export default {
name: '@astrojs/renderer-svelte',
client: './client.js',
server: './server.js',
snowpackPlugin: '@snowpack/plugin-svelte',
snowpackPluginOptions: { compilerOptions: { hydratable: true } },
viteConfig() {
return {
optimizeDeps: {
include: ['@astrojs/renderer-svelte/client.js', 'svelte', 'svelte/internal'],
exclude: ['@astrojs/renderer-svelte/server.js'],
},
plugins: [
svelte({
emitCss: true,
compilerOptions: { hydratable: true },
}),
],
};
},
}

要了解有关 Vite 插件的更多信息,请访问他们的 插件指南

¥To learn more about Vite plugins, please visit their plugin guide.

¥Aliasing

在 Astro v0.21+ 中,可以在 tsconfig.json 中添加导入别名。

¥In Astro v0.21+, import aliases can be added in tsconfig.json.

{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/components/*": ["src/components/*"]
}
}
}

¥File Extensions in Imports

在 Astro v0.21+ 中,文件需要通过其实际扩展名来引用,与磁盘上的扩展名完全相同。在此示例中,Div.tsx 需要被引用为 Div.tsx,而不是 Div.jsx

¥In Astro v0.21+, files need to be referenced by their actual extension, exactly as it is on disk. In this example, Div.tsx would need to be referenced as Div.tsx, not Div.jsx.

import Div from './Div.jsx' // Astro v0.20
import Div from './Div.tsx' // Astro v0.21

同样的更改也适用于像 Div.scss 这样的编译为 css 文件:

¥This same change applies to a compile-to-css file like Div.scss:

<link rel="stylesheet" href={Astro.resolve('./Div.css')}>
<link rel="stylesheet" href={Astro.resolve('./Div.scss')}>

已删除:Frontmatter 中的组件

Section titled 已删除:Frontmatter 中的组件

¥Removed: Components in Frontmatter

以前,你可以使用 JSX 语法而不是 Astro 的组件语法在 Astro Frontmatter 内创建迷你 Astro 组件。这总是有点麻烦,但在新的编译器中它变得不可能支持。我们希望在 Astro 的未来版本中使用不同的非 JSX API 重新引入此功能。

¥Previously, you could create mini Astro Components inside of the Astro Frontmatter, using JSX syntax instead of Astro’s component syntax. This was always a bit of a hack, but in the new compiler it became impossible to support. We hope to re-introduce this feature in a future release of Astro using a different, non-JSX API.

要迁移到 v0.21+,请将所有 JSX Astro 组件(即在另一个组件的 frontmatter 内创建的任何 Astro 组件)转换为独立组件。

¥To migrate to v0.21+, please convert all JSX Astro components (that is, any Astro components created inside of another component’s frontmatter) to standalone components.

¥Styling Changes

¥Autoprefixer

默认情况下不再运行 Autoprefixer。启用:

¥Autoprefixer is no longer run by default. To enable:

  1. Install the latest version (npm install autoprefixer)

  2. Create a postcss.config.cjs file at the root of your project with:

    module.exports = {
    plugins: {
    autoprefixer: {},
    },
    };

确保你已安装 PostCSS。这在以前的版本中是可选的,但现在是必需的:

¥Ensure you have PostCSS installed. This was optional in previous releases, but is required now:

  1. Install the latest version of postcss (npm install -D postcss)

  2. Create a postcss.config.cjs file at the root of your project with:

    module.exports = {
    plugins: {
    tailwindcss: {},
    },
    };

    For more information, read the Tailwind CSS documentation

¥Known Issues

¥Imports on top

在 Astro v0.21+ 中,引入了一个错误,要求组件内部的导入位于 frontmatter 的顶部。

¥In Astro v0.21+, a bug has been introduced that requires imports inside components to be at the top of your frontmatter.

---
import Component from '../components/Component.astro'
const whereShouldIPutMyImports = "on top!"
---
Astro 中文网 - 粤ICP备13048890号