This is the full developer documentation for Astro # 为什么选择 Astro? > Astro 是用于构建内容驱动型网站(如博客、营销和电子商务)的 Web 框架。了解 Astro 为何可能是你下一个网站的不错选择。 Astro 是用于构建内容驱动型网站(如博客、营销和电子商务)的 Web 框架。Astro 因开创了新的 [前端架构](/en/concepts/islands/) 而闻名,与其他框架相比,它可以减少 JavaScript 开销和复杂性。如果你需要一个加载速度快且具有出色 SEO 的网站,那么 Astro 适合你。 ¥**Astro** is the web framework for building **content-driven websites** like blogs, marketing, and e-commerce. Astro is best-known for pioneering a new [frontend architecture](/en/concepts/islands/) to reduce JavaScript overhead and complexity compared to other frameworks. If you need a website that loads fast and has great SEO, then Astro is for you. ## 特性 [Section titled “特性”](#特性) ¥Features Astro 是一个一体化的 Web 框架。它内置了创建网站所需的一切。还有数百种不同的 [integrations](https://astro.build/integrations/) 和 [API 钩子](/en/reference/integrations-reference/) 可用于根据你的具体用例和需求定制项目。 ¥**Astro is an all-in-one web framework.** It includes everything you need to create a website, built-in. There are also hundreds of different [integrations](https://astro.build/integrations/) and [API hooks](/en/reference/integrations-reference/) available to customize a project to your exact use case and needs. 一些亮点包括: ¥Some highlights include: * [群岛](/en/concepts/islands/):针对内容驱动网站进行优化的基于组件的 Web 架构。 * [UI 无关](/en/guides/framework-components/):支持 React、Preact、Svelte、Vue、Solid、HTMX、Web 组件等。 * [服务器优先](/en/guides/on-demand-rendering/):将昂贵的渲染从访问者的设备上移走。 * [默认情况下,零 JS](/en/basics/astro-components/):更少的客户端 JavaScript 会降低网站速度。 * [内容集合](/en/guides/content-collections/):为你的 Markdown 内容组织、验证并提供 TypeScript 类型安全。 * [可定制](/en/guides/integrations-guide/):Partytown、MDX 以及数百种集成可供选择。 ## 设计原则 [Section titled “设计原则”](#设计原则) ¥Design Principles 以下五个核心设计原则可帮助解释我们构建 Astro 的原因、它要解决的问题以及为什么 Astro 可能是你的项目或团队的最佳选择。 ¥Here are five core design principles to help explain why we built Astro, the problems that it exists to solve, and why Astro may be the best choice for your project or team. Astro 是… ¥Astro is… 1. [内容驱动](#content-driven):Astro 旨在展示你的内容。 2. [服务器优先](#server-first):当网站在服务器上渲染 HTML 时,其运行速度会更快。 3. [默认情况下很快](#fast-by-default):在 Astro 中建立一个缓慢的网站应该是不可能的。 4. [便于使用](#easy-to-use):你无需成为专家即可使用 Astro 构建某些东西。 5. [以开发者为中心](#developer-focused):你应该拥有成功所需的资源。 ### 内容驱动 [Section titled “内容驱动”](#内容驱动) ¥Content-driven Astro 专为构建内容丰富的网站而设计。这包括营销网站、发布网站、文档网站、博客、档案、登陆页面、社区网站和电子商务网站。如果你有内容要展示,它需要快速到达你的读者。 ¥**Astro was designed for building content-rich websites.** This includes marketing sites, publishing sites, documentation sites, blogs, portfolios, landing pages, community sites, and e-commerce sites. If you have content to show, it needs to reach your reader quickly. 相比之下,大多数现代 Web 框架都是为构建 Web 应用而设计的。这些框架擅长在浏览器中构建更复杂、类似应用的体验:登录的管理仪表板、收件箱、社交网络、待办事项列表,甚至像 [菲格玛](https://figma.com/) 和 [平](https://ping.gg/) 这样的原生应用。然而,由于这种复杂性,他们在交付内容时可能很难提供出色的性能。 ¥By contrast, most modern web frameworks were designed for building *web applications*. These frameworks excel at building more complex, application-like experiences in the browser: logged-in admin dashboards, inboxes, social networks, todo lists, and even native-like applications like [Figma](https://figma.com/) and [Ping](https://ping.gg/). However with that complexity, they can struggle to provide great performance when delivering your content. Astro 从一开始就专注于内容,作为静态网站构建器,这使得 Astro 能够明智地扩展到高性能、强大、动态的 Web 应用,同时仍然尊重你的内容和受众。Astro 对内容的独特关注让 Astro 能够做出权衡并提供无与伦比的性能功能,而这些功能对于更多以应用为中心的 Web 框架的实现来说是没有意义的。 ¥Astro’s focus on content from its beginnings as a static site builder have allowed Astro to **sensibly scale up to performant, powerful, dynamic web applications** that still respect your content and your audience. Astro’s unique focus on content lets Astro make tradeoffs and deliver unmatched performance features that wouldn’t make sense for more application-focused web frameworks to implement. ### 服务器优先 [Section titled “服务器优先”](#服务器优先) ¥Server-first Astro 尽可能利用浏览器中的服务器渲染而不是客户端渲染。这与传统服务器端框架(PHP、WordPress、Laravel、Ruby on Rails 等)数十年来一直使用的方法相同。但你不需要学习第二种服务器端语言来解锁它。对于 Astro,一切仍然只是 HTML、CSS 和 JavaScript(或者 TypeScript,如果你愿意的话)。 ¥**Astro leverages server rendering over client-side rendering in the browser as much as possible.** This is the same approach that traditional server-side frameworks -- PHP, WordPress, Laravel, Ruby on Rails, etc. -- have been using for decades. But you don’t need to learn a second server-side language to unlock it. With Astro, everything is still just HTML, CSS, and JavaScript (or TypeScript, if you prefer). 这种方法与其他现代 JavaScript Web 框架(如 Next.js、SvelteKit、Nuxt、Remix 等)形成鲜明对比。这些框架是为整个网站的客户端渲染而构建的,并且包括服务器端渲染,主要是为了解决性能问题。与 Astro 的多页应用 (MPA) 方法相比,这种方法被称为单页应用 (SPA)。 ¥This approach stands in contrast to other modern JavaScript web frameworks like Next.js, SvelteKit, Nuxt, Remix, and others. These frameworks were built for client-side rendering of your entire website and include server-side rendering mainly to address performance concerns. This approach has been dubbed the **Single-Page App (SPA)**, in contrast with Astro’s **Multi-Page App (MPA)** approach. SPA 模式有其优点。然而,这些是以额外的复杂性和性能权衡为代价的。这些权衡会损害页面性能(像 [互动时间 (TTI)](https://web.dev/interactive/) 这样的关键指标),这对于首次加载性能至关重要的以内容为中心的网站来说没有多大意义。 ¥The SPA model has its benefits. However, these come at the expense of additional complexity and performance tradeoffs. These tradeoffs harm page performance -- critical metrics like [Time to Interactive (TTI)](https://web.dev/interactive/) -- which doesn’t make much sense for content-focused websites where first-load performance is essential. Astro 的服务器优先方法允许你仅在必要时选择客户端渲染。你可以选择添加在客户端上运行的 UI 框架组件。你可以利用 Astro 的视图转换路由来更好地控制所选页面转换和动画。Astro 的服务器优先渲染(无论是预渲染还是按需渲染)都提供了可以增强和扩展的高性能默认设置。 ¥Astro’s server-first approach allows you to opt in to client-side rendering only if, and exactly as, necessary. You can choose to add UI framework components that run on the client. You can take advantage of Astro’s view transitions router for finer control over select page transitions and animations. Astro’s server-first rendering, either pre-rendered or on-demand, provides performant defaults that you can enhance and extend. ### 默认情况下很快 [Section titled “默认情况下很快”](#默认情况下很快) ¥Fast by default 良好的性能始终很重要,但对于成功取决于内容展示的网站来说尤其重要。事实证明,糟糕的表现会导致你失去参与度、转化率和金钱。例如: ¥Good performance is always important, but it is *especially* critical for websites whose success depends on displaying your content. It has been well-proven that poor performance loses you engagement, conversions, and money. For example: * 每快 100 毫秒 → 转化次数增加 1%([移动化](https://web.dev/why-speed-matters/),收入 + 380,000 美元/年) * 速度提高 50% → 销售额增加 12% ([AutoAnything](https://www.digitalcommerce360.com/2010/08/19/web-accelerator-revs-conversion-and-sales-autoanything/)) * 速度提高 20% → 转化次数增加 10% ([家具村](https://www.thinkwithgoogle.com/intl/en-gb/marketing-strategies/app-and-mobile/furniture-village-and-greenlight-slash-page-load-times-boosting-user-experience/)) * 速度提高 40% → 注册量增加 15% ([兴趣](https://medium.com/pinterest-engineering/driving-user-growth-with-performance-improvements-cfc50dafadd7)) * 速度提高 850 毫秒 → 转化次数增加 7% ([COOK](https://web.dev/why-speed-matters/)) * 每慢 1 秒 → 用户减少 10% ([BBC](https://www.creativebloq.com/features/how-the-bbc-builds-websites-that-scale)) 在许多 Web 框架中,很容易构建一个在开发过程中看起来很棒的网站,但在部署后加载速度却非常慢。JavaScript 通常是罪魁祸首,因为许多手机和低功耗设备很少能与开发者注意本电脑的速度相匹配。 ¥In many web frameworks, it is easy to build a website that looks great during development only to load painfully slow once deployed. JavaScript is often the culprit, since many phones and lower-powered devices rarely match the speed of a developer’s laptop. Astro 的神奇之处在于它如何将上面解释的两个值结合起来 - 以内容为中心与服务器优先的架构 - 以进行权衡并提供其他框架无法提供的功能。结果是每个网站都具有惊人的开箱即用的网络性能。我们的目标:用 Astro 建立一个缓慢的网站几乎是不可能的。 ¥Astro’s magic is in how it combines the two values explained above -- a content focus with a server-first architecture -- to make tradeoffs and deliver features that other frameworks cannot. The result is amazing web performance for every website, out of the box. Our goal: **It should be nearly impossible to build a slow website with Astro.** Astro 网站比使用最流行的 React Web 框架构建的同一网站要好得多。但不要相信我们的话:观看 Astro 的表演离开 Ryan Carniato(Solid.js 和 Marko 的创建者)[speechless](https://youtu.be/2ZEMb_H-LYE?t=8163)。 ¥An Astro website can [load 40% faster with 90% less JavaScript](https://twitter.com/t3dotgg/status/1437195415439360003) than the same site built with the most popular React web framework. But don’t take our word for it: watch Astro’s performance leave Ryan Carniato (creator of Solid.js and Marko) [speechless](https://youtu.be/2ZEMb_H-LYE?t=8163). ### 便于使用 [Section titled “便于使用”](#便于使用) ¥Easy to use Astro 的目标是让每个 Web 开发者都可以使用。Astro 的设计宗旨是让人感觉熟悉且平易近人,无论技能水平或过去的 Web 开发经验如何。 ¥**Astro’s goal is to be accessible to every web developer.** Astro was designed to feel familiar and approachable regardless of skill level or past experience with web development. `.astro` UI 语言是 HTML 的超集:任何有效的 HTML 都是有效的 Astro 模板语法!所以,如果你会编写 HTML,你就能编写 Astro 组件!但是,它还结合了一些我们最喜欢的从其他组件语言借用的功能,例如 JSX 表达式 (React) 和默认的 CSS 作用域(Svelte 和 Vue)。这种与 HTML 的接近性还使得使用渐进增强和常见的可访问性模式变得更加容易,而无需任何开销。 ¥The `.astro` UI language is a superset of HTML: any valid HTML is valid Astro templating syntax! So, if you can write HTML, you can write Astro components! But, it also combines some of our favorite features borrowed from other component languages like JSX expressions (React) and CSS scoping by default (Svelte and Vue). This closeness to HTML also makes it easier to use progressive enhancement and common accessibility patterns without any overhead. 然后,我们确保你还可以使用你最喜欢的、你已经了解的 UI 组件语言,甚至可以重用你可能已经拥有的组件。React、Preact、Svelte、Vue、Solid 和其他组件(包括 Web 组件)均支持在 Astro 项目中创作 UI 组件。 ¥We then made sure that you could also use your favorite UI component languages that you already know, and even reuse components you might already have. React, Preact, Svelte, Vue, Solid, and others, including web components, are all supported for authoring UI components in an Astro project. Astro 的设计比其他 UI 框架和语言简单。造成这种情况的一个重要原因是 Astro 被设计为在服务器上渲染,而不是在浏览器中渲染。这意味着你无需担心:钩子(React)、过时的闭包(也称为 React)、引用(Vue)、可观察量(Svelte)、原子、选择器、反应或派生。服务器上没有反应性,因此所有复杂性都消失了。 ¥Astro was designed to be less complex than other UI frameworks and languages. One big reason for this is that Astro was designed to render on the server, not in the browser. That means that you don’t need to worry about: hooks (React), stale closures (also React), refs (Vue), observables (Svelte), atoms, selectors, reactions, or derivations. There is no reactivity on the server, so all of that complexity melts away. 我们最喜欢的一句话之一是:选择复杂性。我们设计 Astro 是为了尽可能地消除开发者体验中的 “所需的复杂性”,尤其是当你第一次使用时。你可以仅使用 HTML 和 CSS 在 Astro 中构建 “你好世界” 示例网站。然后,当你需要构建更强大的东西时,你可以逐步获取新功能和 API。 ¥One of our favorite sayings is: **opt in to complexity.** We designed Astro to remove as much “required complexity” as possible from the developer experience, especially as you onboard for the first time. You can build a “Hello World” example website in Astro with just HTML and CSS. Then, when you need to build something more powerful, you can incrementally reach for new features and APIs as you go. ### 以开发者为中心 [Section titled “以开发者为中心”](#以开发者为中心) ¥Developer-focused 我们坚信,只有人们喜欢使用 Astro,它才是一个成功的项目。Astro 拥有你使用 Astro 进行构建时所需的一切支持。 ¥We strongly believe that Astro is only a successful project if people love using it. Astro has everything you need to support you as you build with Astro. Astro 投资于开发者工具,例如从你打开终端的那一刻起即可获得出色的 CLI 体验、用于语法高亮的官方 VS Code 扩展、TypeScript 和 Intellisense,以及由数百名社区贡献者积极维护并提供 14 种语言版本的文档。 ¥Astro invests in developer tools like a great CLI experience from the moment you open your terminal, an official VS Code extension for syntax highlighting, TypeScript and Intellisense, and documentation actively maintained by hundreds of community contributors and available in 14 languages. 我们 Discord 上热情、尊重、包容的社区随时准备提供支持、动力和鼓励。打开 `#support` 线程来获取有关你的项目的帮助。访问我们专用的 `#showcase` 通道,分享你的 Astro 网站、博客文章、视频,甚至正在进行的工作,以获得安全反馈和建设性批评。参加定期的在线活动,例如我们的每周社区调用会议、“谈话和记录,” 和 API/bug bashes。 ¥Our welcoming, respectful, inclusive community on Discord is ready to provide support, motivation, and encouragement. Open a `#support` thread to get help with your project. Visit our dedicated `#showcase` channel for sharing your Astro sites, blog posts, videos, and even work-in-progress for safe feedback and constructive criticism. Participate in regular live events such as our weekly community call, “Talking and Doc’ing,” and API/bug bashes. 作为一个开源项目,我们欢迎各种经验水平的社区成员做出各种类型和规模的贡献。我们邀请你加入路由图讨论,以塑造 Astro 的未来,我们希望你能为核心代码库、编译器、文档、语言工具、网站和其他项目贡献修复和功能。 ¥As an open-source project, we welcome contributions of all types and sizes from community members of all experience levels. You are invited to join in roadmap discussions to shape the future of Astro, and we hope you’ll contribute fixes and features to the core codebase, compiler, docs, language tools, websites, and other projects. # Islands 架构 > 了解 Astro 的群岛架构如何帮助保持网站快速运行。 Astro 帮助开创和推广了一种名为 Islands Architecture 的新前端架构模式。Islands 架构的工作原理是将页面的大部分内容渲染为快速、静态的 HTML,并在页面上需要交互性或个性化(例如,图片轮播)时添加较小的 JavaScript “islands”。这避免了单片 JavaScript 负载,这些负载会降低许多其他现代 JavaScript Web 框架的响应速度。 ¥Astro helped pioneer and popularize a new frontend architecture pattern called **Islands Architecture.** Islands architecture works by rendering the majority of your page to fast, static HTML with smaller “islands” of JavaScript added when interactivity or personalization is needed on the page (an image carousel, for example). This avoids the monolithic JavaScript payloads that slow down the responsiveness of many other, modern JavaScript web frameworks. ## 简短的历史 [Section titled “简短的历史”](#简短的历史) ¥A brief history ”组件岛” 一词最初由 Etsy 的前端架构师 [Katie Sylor-Miller](https://sylormiller.com/) 于 2019 年创造。随后 Preact 创建者 Jason Miller 于 2020 年 8 月 11 日在 [这个帖子](https://jasonformat.com/islands-architecture/) 中扩展并记录了这个想法。 ¥The term “component island” was first coined by Etsy’s frontend architect [Katie Sylor-Miller](https://sylormiller.com/) in 2019. This idea was then expanded on and documented in [this post](https://jasonformat.com/islands-architecture/) by Preact creator Jason Miller on August 11, 2020. > ”群岛” 架构的总体思路看似简单:在服务器上渲染 HTML 页面,并在高度动态的区域周围注入占位符或插槽 \[…] 然后可以在客户端上将其 “hydrated” 到小型自包含的小部件中,重用其服务器渲染的初始 HTML。— Jason Miller,Preact 的创建者 > > ¥The general idea of an “Islands” architecture is deceptively simple: render HTML pages on the server, and inject placeholders or slots around highly dynamic regions \[…] that can then be “hydrated” on the client into small self-contained widgets, reusing their server-rendered initial HTML.\ — Jason Miller, Creator of Preact 此架构模式所基于的技术也称为部分或选择性水合。 ¥The technique that this architectural pattern builds on is also known as **partial** or **selective hydration.** 相比之下,大多数基于 JavaScript 的 Web 框架将整个网站合并并渲染为一个大型 JavaScript 应用(也称为单页应用或 SPA)。SPA 提供简单性和功能,但由于客户端 JavaScript 的大量使用而存在页面加载性能问题。 ¥In contrast, most JavaScript-based web frameworks hydrate & render an entire website as one large JavaScript application (also known as a single-page application, or SPA). SPAs provide simplicity and power but suffer from page-load performance problems due to heavy client-side JavaScript usage. SPA 有其一席之地,甚至是 [嵌入 Astro 页面内](/en/guides/migrate-to-astro/from-create-react-app/)。但是,SPA 缺乏选择性和战略性水合的原生能力,这使得它们成为当今网络上大多数项目的严厉选择。 ¥SPAs have their place, even [embedded inside an Astro page](/en/guides/migrate-to-astro/from-create-react-app/). But, SPAs lack the native ability to selectively and strategically hydrate, making them a heavy-handed choice for most projects on the web today. Astro 作为第一个内置选择性水合的主流 JavaScript Web 框架而广受欢迎,它使用了 Sylor-Miller 首次提出的相同组件岛模式。从那时起,我们就在 Sylor-Miller 的原创作品的基础上进行了扩展和发展,这有助于激发类似的组件岛方法来动态服务器渲染内容。 ¥Astro became popular as the first mainstream JavaScript web framework with selective hydration built-in, using that same component islands pattern first coined by Sylor-Miller. We’ve since expanded and evolved on Sylor-Miller’s original work, which helped to inspire a similar component island approach to dynamically server-rendered content. ## 什么是群岛? [Section titled “什么是群岛?”](#什么是群岛) ¥What is an island? 在 Astro 中,群岛是 HTML 静态页面上的增强型 UI 组件。 ¥In Astro, an island is an enhanced UI component on an otherwise static page of HTML. [**客户端岛**](#client-islands) 是一个交互式 JavaScript UI 组件,它与页面的其余部分分开进行水化,而 [**服务器岛**](#server-islands) 是一个 UI 组件,它将其动态内容与页面的其余部分分开进行服务器渲染。 ¥A [**client island**](#client-islands) is an interactive JavaScript UI component that is hydrated separately from the rest of the page, while a [**server island**](#server-islands) is a UI component that server-renders its dynamic content separately from the rest of the page. 为了优化页面加载,两个群岛都以每个组件为基础独立运行昂贵或较慢的进程。 ¥Both islands run expensive or slower processes independently, on a per-component basis, for optimized page loads. ## Island 组件 [Section titled “Island 组件”](#island-组件) ¥Island components Astro 组件是页面模板的构建块。它们渲染为静态 HTML,没有客户端运行时。 ¥Astro components are the building blocks of your page template. They render to static HTML with no client-side runtime. 将客户端岛想象成一个交互式小部件,漂浮在一片静态、轻量级、服务器渲染的 HTML 海洋中。可以为个性化或动态服务器渲染元素添加服务器岛,例如登录访问者的个人资料图片。 ¥Think of a client island as an interactive widget floating in a sea of otherwise static, lightweight, server-rendered HTML. Server islands can be added for personalized or dynamic server-rendered elements, such as a logged in visitor’s profile picture. Header (interactive island) Sidebar (static HTML) 静态内容,如文本、图片等。 ¥Static content like text, images, etc. Image carousel (interactive island) Footer (static HTML) Source: [Islands Architecture: Jason Miller](https://jasonformat.com/islands-architecture/) 一个孤岛始终与页面上的其他孤岛隔离运行,并且一个页面上可以存在多个孤岛。即使客户端岛在不同的组件上下文中运行,它们仍然可以共享状态并相互通信。 ¥An island always runs in isolation from other islands on the page, and multiple islands can exist on a page. Client islands can still share state and communicate with each other, even though they run in different component contexts. 这种灵活性使 Astro 能够支持多种 UI 框架,例如 [React](https://react.nodejs.cn/)、[Preact](https://preact.nodejs.cn/)、[Svelte](https://svelte.nodejs.cn/)、[Vue](https://vuejs.org/) 和 [SolidJS](https://www.solidjs.com/)。因为它们是独立的,所以你甚至可以在每个页面上混合使用多个框架。 ¥This flexibility allows Astro to support multiple UI frameworks like [React](https://react.nodejs.cn/), [Preact](https://preact.nodejs.cn/), [Svelte](https://svelte.nodejs.cn/), [Vue](https://vuejs.org/), and [SolidJS](https://www.solidjs.com/). Because they are independent, you can even mix several frameworks on each page. Tip Although most developers will stick to just one UI framework, Astro supports multiple frameworks in the same project. This allows you to: * Choose the framework that is best for each component. * Learn a new framework without needing to start a new project. * Collaborate with others even when working in different frameworks. * Incrementally convert an existing site to another framework with no downtime. ## 客户端岛 [Section titled “客户端岛”](#客户端岛) ¥Client Islands 默认情况下,Astro 会自动将每个 UI 组件渲染为 HTML 和 CSS,自动删除所有客户端 JavaScript。 ¥By default, Astro will automatically render every UI component to just HTML & CSS, **stripping out all client-side JavaScript automatically.** src/pages/index.astro ```astro ``` 这听起来可能很严格,但这种行为默认情况下可以保持 Astro 网站的快速运行,并防止开发者意外发送不必要或不需要的 JavaScript,从而降低其网站速度。 ¥This may sound strict, but this behavior is what keeps Astro websites fast by default and protects developers from accidentally sending unnecessary or unwanted JavaScript that might slow down their website. 将任何静态 UI 组件变成交互式岛只需要 `client:*` 指令。然后,Astro 会自动构建并打包你的客户端 JavaScript 以优化性能。 ¥Turning any static UI component into an interactive island requires only a `client:*` directive. Astro then automatically builds and bundles your client-side JavaScript for optimized performance. src/pages/index.astro ```astro ``` 对于孤岛,仅为使用 `client:*` 指令标记的显式交互组件加载客户端 JavaScript。 ¥With islands, client-side JavaScript is only loaded for the explicit interactive components that you mark using `client:*` directives. 而且由于交互是在组件级别配置的,因此你可以根据每个组件的使用情况处理不同的加载优先级。例如,`client:idle` 告诉组件在浏览器空闲时加载,而 `client:visible` 告诉组件仅在进入视口时加载。 ¥And because interaction is configured at the component-level, you can handle different loading priorities for each component based on its usage. For example, `client:idle` tells a component to load when the browser becomes idle, and `client:visible` tells a component to load only once it enters the viewport. ### Benefits of client islands 使用 Astro 群岛构建的最明显的好处是性能:你网站的大部分内容都会转换为快速、静态的 HTML,并且仅为需要它的各个组件加载 JavaScript。JavaScript 是按字节加载最慢的资源之一,因此每个字节都很重要。 ¥The most obvious benefit of building with Astro Islands is performance: the majority of your website is converted to fast, static HTML and JavaScript is only loaded for the individual components that need it. JavaScript is one of the slowest assets that you can load per-byte, so every byte counts. 另一个好处是并行加载。在上面的示例图中,低优先级 “图片轮播” 岛不需要阻挡高优先级 “header” 岛。两者并行加载并独立进行水合,这意味着标题立即变得可交互,而无需等待页面下方较重的轮播。 ¥Another benefit is parallel loading. In the example illustration above, the low-priority “image carousel” island doesn’t need to block the high-priority “header” island. The two load in parallel and hydrate in isolation, meaning that the header becomes interactive immediately without having to wait for the heavier carousel lower down the page. 更好的是,你可以准确地告诉 Astro 如何以及何时渲染每个组件。如果该图片轮播的加载成本确实很高,你可以附加一个特殊的 [客户指令](/en/reference/directives-reference/#client-directives),告诉 Astro 仅当轮播在页面上可见时才加载该轮播。如果用户从未看到它,则它永远不会加载。 ¥Even better, you can tell Astro exactly how and when to render each component. If that image carousel is really expensive to load, you can attach a special [client directive](/en/reference/directives-reference/#client-directives) that tells Astro to only load the carousel when it becomes visible on the page. If the user never sees it, it never loads. 在 Astro 中,作为开发者,你需要明确告诉 Astro 页面上的哪些组件也需要在浏览器中运行。Astro 只会水化页面上所需的内容,并将网站的其余部分保留为静态 HTML。 ¥In Astro, it’s up to you as the developer to explicitly tell Astro which components on the page need to also run in the browser. Astro will only hydrate exactly what’s needed on the page and leave the rest of your site as static HTML. **客户端岛是 Astro 默认快速性能故事的秘密!** ¥**Client islands are the secret to Astro’s fast-by-default performance story!** Read more about [using JavaScript framework components](/en/guides/framework-components/) in your project. ## 服务器岛 [Section titled “服务器岛”](#服务器岛) ¥Server islands 服务器岛是一种将昂贵或缓慢的服务器端代码移出主渲染过程的方法,可轻松组合高性能静态 HTML 和动态服务器生成的组件。 ¥Server islands are a way to move expensive or slow server-side code out of the way of the main rendering process, making it easy to combine high-performance static HTML and dynamic server-generated components. 将 [`server:defer` 指令](/en/reference/directives-reference/#server-directives) 添加到你页面上的任何 Astro 组件,将其变成自己的服务器岛: ¥Add the [`server:defer` directive](/en/reference/directives-reference/#server-directives) to any Astro component on your page to turn it into its own server island: src/pages/index.astro ```astro --- import Avatar from "../components/Avatar.astro"; --- ``` 这会将你的页面分解为较小的服务器渲染内容区域,每个区域都并行加载。 ¥This breaks up your page with smaller areas of server-rendered content that each load in parallel. 你的页面的主要内容可以立即使用占位符内容渲染,例如通用头像,直到你的群岛自己的内容可用。使用服务器岛,拥有个性化内容的小组件不会延迟静态页面的渲染。 ¥Your page’s main content can be rendered immediately with placeholder content, such as a generic avatar until your island’s own content is available. With server islands, having small components of personalized content does not delay the rendering of an otherwise static page. 此渲染模式是为可移植而构建的。它不依赖于任何服务器基础设施,因此它可以与任何主机一起使用,从 Docker 容器中的 Node.js 服务器到你选择的无服务器提供商。 ¥This rendering pattern was built to be portable. It does not depend on any server infrastructure so it will work with any host, from a Node.js server in a Docker container to the serverless provider of your choice. ### Benefits of server islands 服务器岛的一个好处是能够动态渲染页面中动态程度更高的部分。这允许更积极地缓存外壳和主要内容,从而提供更快的性能。 ¥One benefit of server islands is the ability to render the more highly dynamic parts of your page on the fly. This allows the outer shell and main content to be more aggressively cached, providing faster performance. 另一个好处是提供出色的访客体验。服务器岛经过优化,加载速度快,通常甚至在浏览器绘制页面之前。但在群岛渲染所需的短暂时间内,你可以显示自定义后备内容并防止任何布局偏移。 ¥Another benefit is providing a great visitor experience. Server islands are optimized and load quickly, often even before the browser has even painted the page. But in the short time it takes for your islands to render, you can display custom fallback content and prevent any layout shift. 受益于 Astro 服务器岛的站点示例是电子商务店面。虽然产品页面的主要内容很少更改,但这些页面通常包含一些动态部分: ¥An example of a site that benefits from Astro’s server islands is an e-commerce storefront. Although the main content of product pages change infrequently, these pages typically have some dynamic pieces: * 标题中的用户头像。 * 产品的特别优惠和销售。 * 用户评论。 使用这些元素的服务器岛,你的访问者将立即看到页面的最重要部分,即你的产品。通用头像、加载旋转器和商店公告可以显示为后备内容,直到个性化部分可用。 ¥Using server islands for these elements, your visitor will see the most important part of the page, your product, immediately. Generic avatars, loading spinners, and store announcements can be displayed as fallback content until the personalized parts are available. Read more about [using server islands](/en/guides/server-islands/) in your project. # 安装 Astro > 如何安装 Astro 并启动新项目。 [`create astro` CLI 命令](#install-from-the-cli-wizard) 是从头开始启动新 Astro 项目的最快方法。它将引导你完成设置新 Astro 项目的每个步骤,并允许你从几个不同的官方入门模板中进行选择。 ¥The [`create astro` CLI command](#install-from-the-cli-wizard) is the fastest way to start a new Astro project from scratch. It will walk you through every step of setting up your new Astro project and allow you to choose from a few different official starter templates. 你还可以使用 `template` 标志运行 CLI 命令,以使用任何现有主题或入门模板开始你的项目。探索我们的 [主题和入门展示](https://astro.build/themes/),你可以在其中浏览博客、作品集、文档站点、登录页面等主题! ¥You can also run the CLI command with the `template` flag to begin your project using any existing theme or starter template. Explore our [themes and starters showcase](https://astro.build/themes/) where you can browse themes for blogs, portfolios, documentation sites, landing pages, and more! 要手动安装 Astro,请参阅我们的 [分步手动安装指南](#manual-setup)。 ¥To install Astro manually instead, see our [step-by-step manual installation guide](#manual-setup). Online previews Prefer to try Astro in your browser? Visit [astro.new](https://astro.new/) to browse our starter templates and spin up a new Astro project without ever leaving your browser. ## 先决条件 [Section titled “先决条件”](#先决条件) ¥Prerequisites * Node.js - `v18.20.8` 或 `v20.3.0`、`v22.0.0` 或更高版本。(不支持 `v19` 和 `v21`。) * 文本编辑器 - 我们建议将 [VS Code](https://code.visualstudio.com/) 与我们的 [官方 Astro 扩展](https://marketplace.visualstudio.com/items?itemName=astro-build.astro-vscode) 一起使用。 * 终端 - Astro 可通过其命令行接口 (CLI) 访问。 ## 浏览器兼容性 [Section titled “浏览器兼容性”](#浏览器兼容性) ¥Browser compatibility Astro 是使用 Vite 构建的,默认情况下针对具有现代 JavaScript 支持的浏览器。有关完整参考,请参阅 [Vite 中当前支持的浏览器版本列表](https://vite.dev/guide/build.html#browser-compatibility)。 ¥Astro is built with Vite which targets browsers with modern JavaScript support by default. For a complete reference, you can see the [list of currently supported browser versions in Vite](https://vite.dev/guide/build.html#browser-compatibility). ## 从 CLI 向导安装 [Section titled “从 CLI 向导安装”](#从-cli-向导安装) ¥Install from the CLI wizard 你可以在机器上的任何地方运行 `create astro`,因此在开始之前无需为项目创建新的空目录。如果你还没有新项目的空目录,向导将帮助你自动创建一个。 ¥You can run `create astro` anywhere on your machine, so there’s no need to create a new empty directory for your project before you begin. If you don’t have an empty directory yet for your new project, the wizard will help create one for you automatically. 1. Run the following command in your terminal to start the install wizard: * npm ```shell # create a new project with npm npm create astro@latest ``` * pnpm ```shell # create a new project with pnpm pnpm create astro@latest ``` * Yarn ```shell # create a new project with yarn yarn create astro ``` If all goes well, you will see a success message followed by some recommended next steps. 2. Now that your project has been created, you can `cd` into your new project directory to begin using Astro. 3. If you skipped the “Install dependencies?” step during the CLI wizard, then be sure to install your dependencies before continuing. * npm ```shell npm install ``` * pnpm ```shell pnpm install ``` * Yarn ```shell yarn install ``` 4. You can now [start the Astro dev server](/en/develop-and-build/#start-the-astro-dev-server) and see a live preview of your project while you build! ## CLI 安装标志 [Section titled “CLI 安装标志”](#cli-安装标志) ¥CLI installation flags 你可以使用其他标志运行 `create astro` 命令来自定义设置过程(例如,回答 “yes” 的所有问题、跳过休斯顿动画)或新项目(例如,是否安装 git、添加集成)。 ¥You can run the `create astro` command with additional flags to customize the setup process (e.g. answering “yes” to all questions, skipping the Houston animation) or your new project (e.g. install git or not, add integrations). See [all the available `create astro` command flags](https://github.com/withastro/astro/blob/main/packages/create-astro/README.md) ### 添加集成 [Section titled “添加集成”](#添加集成) ¥Add integrations 你可以通过将 `--add` 参数传递给 `create astro` 命令来启动一个新的 Astro 项目并同时安装任何支持 `astro add` 命令的 [官方集成](/en/guides/integrations-guide/) 或社区集成。 ¥You can start a new Astro project and install any [official integrations](/en/guides/integrations-guide/) or community integrations that support the `astro add` command at the same time by passing the `--add` argument to the `create astro` command. 在你的终端中运行以下命令,替换支持 `astro add` 命令的任何集成: ¥Run the following command in your terminal, substituting any integration that supports the `astro add` command: * npm ```shell # create a new project with React and Partytown npm create astro@latest -- --add react --add partytown ``` * pnpm ```shell # create a new project with React and Partytown pnpm create astro@latest --add react --add partytown ``` * Yarn ```shell # create a new project with React and Partytown yarn create astro --add react --add partytown ``` ### 使用主题或入门模板 [Section titled “使用主题或入门模板”](#使用主题或入门模板) ¥Use a theme or starter template 你可以通过将 `--template` 参数传递给 `create astro` 命令,基于任何 GitHub 存储库的 [官方示例](https://github.com/withastro/astro/tree/main/examples) 或 `main` 分支启动一个新的 Astro 项目。 ¥You can start a new Astro project based on an [official example](https://github.com/withastro/astro/tree/main/examples) or the `main` branch of any GitHub repository by passing a `--template` argument to the `create astro` command. 在你的终端中运行以下命令,替换官方 Astro 入门模板名称或你要使用的主题的 GitHub 用户名和存储库: ¥Run the following command in your terminal, substituting the official Astro starter template name, or the GitHub username and repository of the theme you want to use: * npm ```shell # create a new project with an official example npm create astro@latest -- --template # create a new project based on a GitHub repository’s main branch npm create astro@latest -- --template / ``` * pnpm ```shell # create a new project with an official example pnpm create astro@latest --template # create a new project based on a GitHub repository’s main branch pnpm create astro@latest --template / ``` * Yarn ```shell # create a new project with an official example yarn create astro --template # create a new project based on a GitHub repository’s main branch yarn create astro --template / ``` 默认情况下,此命令将使用模板存储库的 `main` 分支。要使用不同的分支名称,请将其作为 `--template` 参数的一部分传递:`/#`。 ¥By default, this command will use the template repository’s `main` branch. To use a different branch name, pass it as part of the `--template` argument: `/#`. ## 手动设置 [Section titled “手动设置”](#手动设置) ¥Manual Setup 本指南将引导你完成手动安装和配置新 Astro 项目的步骤。 ¥This guide will walk you through the steps to manually install and configure a new Astro project. 如果你不想使用我们的自动 `create astro` CLI 工具,你可以按照以下指南自行设置你的项目。 ¥If you prefer not to use our automatic `create astro` CLI tool, you can set up your project yourself by following the guide below. 1. Create your directory Create an empty directory with the name of your project, and then navigate into it. ```bash mkdir my-astro-project cd my-astro-project ``` Once you are in your new directory, create your project `package.json` file. This is how you will manage your project dependencies, including Astro. If you aren’t familiar with this file format, run the following command to create one. * npm ```shell npm init --yes ``` * pnpm ```shell pnpm init ``` * Yarn ```shell yarn init --yes ``` 2. Install Astro First, install the Astro project dependencies inside your project. Important Astro must be installed locally, not globally. Make sure you are *not* running `npm install -g astro` `pnpm add -g astro` or `yarn add global astro`. * npm ```shell npm install astro ``` * pnpm ```shell pnpm add astro ``` * Yarn ```shell yarn add astro ``` Then, replace any placeholder “scripts” section of your `package.json` with the following: package.json ```diff { "scripts": { -"test": "echo \"Error: no test specified\" && exit 1", +"dev": "astro dev", +"build": "astro build", +"preview": "astro preview" }, } ``` You’ll use these scripts later in the guide to start Astro and run its different commands. 3. Create your first page In your text editor, create a new file in your directory at `src/pages/index.astro`. This will be your first Astro page in the project. For this guide, copy and paste the following code snippet (including `---` dashes) into your new file: src/pages/index.astro ```astro --- // Welcome to Astro! Everything between these triple-dash code fences // is your "component frontmatter". It never runs in the browser. console.log('This runs in your terminal, not the browser!'); ---

Hello, World!

``` 4. Create your first static asset You will also want to create a `public/` directory to store your static assets. Astro will always include these assets in your final build, so you can safely reference them from inside your component templates. In your text editor, create a new file in your directory at `public/robots.txt`. `robots.txt` is a simple file that most sites will include to tell search bots like Google how to treat your site. For this guide, copy and paste the following code snippet into your new file: public/robots.txt ```diff # Example: Allow all bots to scan and index your site. # Full syntax: https://developers.google.com/search/docs/advanced/robots/create-robots-txt User-agent: * Allow: / ``` 5. Create `astro.config.mjs` Astro is configured using `astro.config.mjs`. This file is optional if you do not need to configure Astro, but you may wish to create it now. Create `astro.config.mjs` at the root of your project, and copy the code below into it: astro.config.mjs ```js import { defineConfig } from "astro/config"; // https://astro.build/config export default defineConfig({}); ``` If you want to include [UI framework components](/en/guides/framework-components/) such as React, Svelte, etc. or use other tools such as MDX or Partytown in your project, here is where you will [manually import and configure integrations](/en/guides/integrations-guide/). Read Astro’s [API configuration reference](/en/reference/configuration-reference/) for more information. 6. Add TypeScript support TypeScript is configured using `tsconfig.json`. Even if you don’t write TypeScript code, this file is important so that tools like Astro and VS Code know how to understand your project. Some features (like npm package imports) aren’t fully supported in the editor without a `tsconfig.json` file. If you do intend to write TypeScript code, using Astro’s `strict` or `strictest` template is recommended. You can view and compare the three template configurations at [astro/tsconfigs/](https://github.com/withastro/astro/blob/main/packages/astro/tsconfigs/). Create `tsconfig.json` at the root of your project, and copy the code below into it. (You can use `base`, `strict`, or `strictest` for your TypeScript template): tsconfig.json ```json { "extends": "astro/tsconfigs/base" } ``` Read Astro’s [TypeScript setup guide](/en/guides/typescript/#setup) for more information. 7. Next Steps If you have followed the steps above, your project directory should now look like this: * node\_modules/ * … * public/ * robots.txt * src/ * pages/ * index.astro * astro.config.mjs * package-lock.json or `yarn.lock`, `pnpm-lock.yaml`, etc. * package.json * tsconfig.json 8. You can now [start the Astro dev server](/en/develop-and-build/#start-the-astro-dev-server) and see a live preview of your project while you build! # 项目结构 > Astro 项目基本文件结构简介。 从 `create astro` CLI 向导生成的新 Astro 项目已经包含一些文件和文件夹。其他的,你将自己创建并添加到 Astro 的现有文件结构中。 ¥Your new Astro project generated from the `create astro` CLI wizard already includes some files and folders. Others, you will create yourself and add to Astro’s existing file structure. 以下是 Astro 项目的组织方式,以及你将在新项目中找到的一些文件。 ¥Here’s how an Astro project is organized, and some files you will find in your new project. ## 目录和文件 [Section titled “目录和文件”](#目录和文件) ¥Directories and Files Astro 为你的项目利用有态度的文件夹布局。每个 Astro 项目根目录应包含以下目录和文件: ¥Astro leverages an opinionated folder layout for your project. Every Astro project root should include the following directories and files: * `src/*` - 你的项目源代码(组件、页面、样式、图片等) * `public/*` - 你的非代码、未处理的资源(字体、图标等) * `package.json` - 项目清单。 * `astro.config.mjs` - Astro 配置文件。(受到推崇的) * `tsconfig.json` - TypeScript 配置文件。(受到推崇的) ### 示例项目树 [Section titled “示例项目树”](#示例项目树) ¥Example Project Tree 常见的 Astro 项目目录可能如下所示: ¥A common Astro project directory might look like this: * public/ * robots.txt * favicon.svg * my-cv.pdf * src/ * blog/ * post1.md * post2.md * post3.md * components/ * Header.astro * Button.jsx * images/ * image1.jpg * image2.jpg * image3.jpg * layouts/ * PostLayout.astro * pages/ * posts/ * \[post].astro * about.astro * **index.astro** * rss.xml.js * styles/ * global.css * content.config.ts * astro.config.mjs * package.json * tsconfig.json ### `src/` [Section titled “src/”](#src) `src/` 文件夹是大部分项目源代码所在的位置。这包括: ¥The `src/` folder is where most of your project source code lives. This includes: * [页面](/en/basics/astro-pages/) * [布局](/en/basics/layouts/) * [Astro 组件](/en/basics/astro-components/) * [UI 框架组件(React 等)](/en/guides/framework-components/) * [样式(CSS、Sass)](/en/guides/styling/) * [Markdown](/en/guides/markdown-content/) * [Astro 要优化和处理的图片](/en/guides/images/) Astro 处理、优化和打包你的 `src/` 文件以创建发送到浏览器的最终网站。与静态 `public/` 目录不同,你的 `src/` 文件是由 Astro 为你构建和处理的。 ¥Astro processes, optimizes, and bundles your `src/` files to create the final website that is shipped to the browser. Unlike the static `public/` directory, your `src/` files are built and handled for you by Astro. 有些文件(如 Astro 组件)甚至不会按写入方式发送到浏览器,而是渲染为静态 HTML。其他文件(如 CSS)会发送到浏览器,但可能会进行优化或与其他 CSS 文件打包在一起以提高性能。 ¥Some files (like Astro components) are not even sent to the browser as written but are instead rendered to static HTML. Other files (like CSS) are sent to the browser but may be optimized or bundled with other CSS files for performance. Tip While this guide describes some popular conventions used in the Astro community, the only directory reserved by Astro is `src/pages/`. You are free to rename and reorganize any other directories in a way that works best for you. ### `src/pages` [Section titled “src/pages”](#srcpages) 通过将 [支持的文件类型](/en/basics/astro-pages/#supported-page-files) 添加到此目录,可以为你的网站创建页面路由。 ¥Pages routes are created for your site by adding [supported file types](/en/basics/astro-pages/#supported-page-files) to this directory. Caution `src/pages` is a **required** sub-directory in your Astro project. Without it, your site will have no pages or routes! ### `src/components` [Section titled “src/components”](#srccomponents) 组件是 HTML 页面的可重复使用代码单元。这些可能是 [Astro 组件](/en/basics/astro-components/) 或 [UI 框架组件](/en/guides/framework-components/),例如 React 或 Vue。通常在此文件夹中将所有项目组件分组和组织在一起。 ¥**Components** are reusable units of code for your HTML pages. These could be [Astro components](/en/basics/astro-components/), or [UI framework components](/en/guides/framework-components/) like React or Vue. It is common to group and organize all of your project components together in this folder. 这是 Astro 项目中的常见约定,但不是必需的。你可以随意组织你的组件! ¥This is a common convention in Astro projects, but it is not required. Feel free to organize your components however you like! ### `src/layouts` [Section titled “src/layouts”](#srclayouts) [布局](/en/basics/layouts/) 是 Astro 组件,定义一个或多个 [pages](/en/basics/astro-pages/) 共享的 UI 结构。 ¥[Layouts](/en/basics/layouts/) are Astro components that define the UI structure shared by one or more [pages](/en/basics/astro-pages/). 就像 `src/components` 一样,该目录是通用约定,但不是必需的。 ¥Just like `src/components`, this directory is a common convention but not required. ### `src/styles` [Section titled “src/styles”](#srcstyles) 将 CSS 或 Sass 文件存储在 `src/styles` 目录中是一种常见约定,但这不是必需的。只要你的样式位于 `src/` 目录中的某个位置并且正确导入,Astro 就会处理和优化它们。 ¥It is a common convention to store your CSS or Sass files in a `src/styles` directory, but this is not required. As long as your styles live somewhere in the `src/` directory and are imported correctly, Astro will handle and optimize them. ### `public/` [Section titled “public/”](#public) `public/` 目录用于存放项目中在 Astro 构建过程中不需要处理的文件和资源。此文件夹中的文件将原封不动地复制到构建文件夹中,然后将构建你的站点。 ¥The `public/` directory is for files and assets in your project that do not need to be processed during Astro’s build process. The files in this folder will be copied into the build folder untouched, and then your site will be built. 此行为使 `public/` 成为不需要任何处理的常见资源的理想选择,例如某些图片和字体,或特殊文件,例如 `robots.txt` 和 `manifest.webmanifest`。 ¥This behavior makes `public/` ideal for common assets that do not require any processing, like some images and fonts, or special files such as `robots.txt` and `manifest.webmanifest`. 你可以将 CSS 和 JavaScript 放置在 `public/` 目录中,但请注意,这些文件不会在你的最终版本中打包或优化。 ¥You can place CSS and JavaScript in your `public/` directory, but be aware that those files will not be bundled or optimized in your final build. Tip As a general rule, any CSS or JavaScript that you write yourself should live in your `src/` directory. ### `package.json` [Section titled “package.json”](#packagejson) 这是 JavaScript 包管理器用来管理依赖的文件。它还定义了通常用于运行 Astro 的脚本(例如:`npm run dev`、`npm run build`)。 ¥This is a file used by JavaScript package managers to manage your dependencies. It also defines the scripts that are commonly used to run Astro (ex: `npm run dev`, `npm run build`). 你可以在 `package.json` 中指定 [两种依赖](https://npm.nodejs.cn/specifying-dependencies-and-devdependencies-in-a-package-json-file):`dependencies` 和 `devDependencies`。在大多数情况下,它们的工作原理是相同的:Astro 在构建时需要所有依赖,并且你的包管理器将安装这两个依赖。我们建议将所有依赖放在 `dependencies` 中启动,并且仅在你发现特定需要时才使用 `devDependencies`。 ¥There are [two kinds of dependencies](https://npm.nodejs.cn/specifying-dependencies-and-devdependencies-in-a-package-json-file) you can specify in a `package.json`: `dependencies` and `devDependencies`. In most cases, these work the same: Astro needs all dependencies at build time, and your package manager will install both. We recommend putting all of your dependencies in `dependencies` to start, and only use `devDependencies` if you find a specific need to do so. 如需为你的项目创建新的 `package.json` 文件的帮助,请查看 [手动设置](/en/install-and-setup/#manual-setup) 说明。 ¥For help creating a new `package.json` file for your project, check out the [manual setup](/en/install-and-setup/#manual-setup) instructions. ### `astro.config.mjs` [Section titled “astro.config.mjs”](#astroconfigmjs) 该文件在每个入门模板中生成,并包含 Astro 项目的配置选项。你可以在此处指定要使用的集成、构建选项、服务器选项等。 ¥This file is generated in every starter template and includes configuration options for your Astro project. Here you can specify integrations to use, build options, server options, and more. Astro 支持多种 JavaScript 配置文件格式:`astro.config.js`、`astro.config.mjs`、`astro.config.cjs` 和 `astro.config.ts`。我们建议在大多数情况下使用 `.mjs`,如果你想在配置文件中编写 TypeScript,我们建议使用 `.ts`。 ¥Astro supports several file formats for its JavaScript configuration file: `astro.config.js`, `astro.config.mjs`, `astro.config.cjs` and `astro.config.ts`. We recommend using `.mjs` in most cases or `.ts` if you want to write TypeScript in your config file. TypeScript 配置文件加载使用 [`tsm`](https://github.com/lukeed/tsm) 处理,并将尊重你项目的 `tsconfig` 选项。 ¥TypeScript config file loading is handled using [`tsm`](https://github.com/lukeed/tsm) and will respect your project’s `tsconfig` options. 有关完整详细信息,请参阅 [配置参考](/en/reference/configuration-reference/)。 ¥See the [configuration reference](/en/reference/configuration-reference/) for complete details. ### `tsconfig.json` [Section titled “tsconfig.json”](#tsconfigjson) 该文件在每个入门模板中生成,并包含 Astro 项目的 TypeScript 配置选项。如果没有 `tsconfig.json` 文件,编辑器将无法完全支持某些功能(例如 npm 包导入)。 ¥This file is generated in every starter template and includes TypeScript configuration options for your Astro project. Some features (like npm package imports) aren’t fully supported in the editor without a `tsconfig.json` file. 有关设置配置的详细信息,请参阅 [TypeScript 指南](/en/guides/typescript/)。 ¥See the [TypeScript Guide](/en/guides/typescript/) for details on setting configurations. # 开发和构建 > 如何开始新项目。 一旦你拥有 Astro 项目,你就可以使用 Astro 进行构建了!🚀 ¥Once you have an Astro project, now you’re ready to build with Astro! 🚀 ## 编辑你的项目 [Section titled “编辑你的项目”](#编辑你的项目) ¥Edit your project 要更改你的项目,请在代码编辑器中打开你的项目文件夹。在开发模式下运行开发服务器,你可以在编辑代码时查看网站的更新。 ¥To make changes to your project, open your project folder in your code editor. Working in development mode with the dev server running allows you to see updates to your site as you edit the code. 你还可以配置 TypeScript 或安装官方 Astro 编辑器扩展等 [自定义开发环境的各个方面](#configure-your-dev-environment)。 ¥You can also [customize aspects of your development environment](#configure-your-dev-environment) such as configuring TypeScript or installing the official Astro editor extensions. ### 启动 Astro 开发服务器 [Section titled “启动 Astro 开发服务器”](#启动-astro-开发服务器) ¥Start the Astro dev server Astro 配备了内置开发服务器,其中包含项目开发所需的一切。`astro dev` CLI 命令将启动本地开发服务器,以便你可以第一次看到新网站的运行情况。 ¥Astro comes with a built-in development server that has everything you need for project development. The `astro dev` CLI command will start the local development server so that you can see your new website in action for the very first time. 每个入门模板都附带一个预配置的脚本,将为你运行 `astro dev`。导航到你的项目目录后,使用你最喜欢的包管理器运行此命令并启动 Astro 开发服务器。 ¥Every starter template comes with a pre-configured script that will run `astro dev` for you. After navigating into your project directory, use your favorite package manager to run this command and start the Astro development server. * npm ```shell npm run dev ``` * pnpm ```shell pnpm run dev ``` * yarn ```shell yarn run dev ``` 如果一切顺利,Astro 现在将在 上为你的项目提供服务。访问浏览器中的该链接并查看你的新网站! ¥If all goes well, Astro will now be serving your project on . Visit that link in your browser and see your new site! ### 在开发模式下工作 [Section titled “在开发模式下工作”](#在开发模式下工作) ¥Work in development mode Astro 将监听 `src/` 目录中的实时文件更改,并在构建时更新站点预览,因此你在开发过程中进行更改时无需重新启动服务器。当开发服务器运行时,你将始终能够在浏览器中看到你网站的最新版本。 ¥Astro will listen for live file changes in your `src/` directory and update your site preview as you build, so you will not need to restart the server as you make changes during development. You will always be able to see an up-to-date version of your site in your browser when the dev server is running. 在浏览器中查看你的网站时,你将可以访问 [Astro 开发工具栏](/en/guides/dev-toolbar/)。在你构建时,它将帮助你检查 [islands](/en/concepts/islands/)、发现可访问性问题等。 ¥When viewing your site in the browser, you’ll have access to the [Astro dev toolbar](/en/guides/dev-toolbar/). As you build, it will help you inspect your [islands](/en/concepts/islands/), spot accessibility issues, and more. 如果启动开发服务器后无法在浏览器中打开项目,请返回运行 `dev` 命令的终端并检查显示的消息。它应该告诉你是否发生了错误,或者你的项目是否在与​​ 不同的 URL 上提供服务。 ¥If you aren’t able to open your project in the browser after starting the dev server, go back to the terminal where you ran the `dev` command and check the message displayed. It should tell you if an error occurred, or if your project is being served at a different URL than . ## 构建和预览你的网站 [Section titled “构建和预览你的网站”](#构建和预览你的网站) ¥Build and preview your site 要检查将在构建时创建的站点版本,请退出开发服务器 (`Ctrl` + `C`) 并在终端中为你的包管理器运行适当的构建命令: ¥To check the version of your site that will be created at build time, quit the dev server (`Ctrl` + `C`) and run the appropriate build command for your package manager in your terminal: * npm ```shell npm run build ``` * pnpm ```shell pnpm build ``` * yarn ```shell yarn run build ``` Astro 将在单独的文件夹(默认为 `dist/`)中构建可部署的站点版本,你可以在终端中查看其进度。这将在你部署到生产之前提醒你项目中的任何构建错误。如果 TypeScript 配置为 `strict` 或 `strictest`,`build` 脚本还将检查你的项目是否存在类型错误。 ¥Astro will build a deploy-ready version of your site in a separate folder (`dist/` by default) and you can watch its progress in the terminal. This will alert you to any build errors in your project before you deploy to production. If TypeScript is configured to `strict` or `strictest`, the `build` script will also check your project for type errors. 构建完成后,在你的终端中运行适当的 `preview` 命令(例如 `npm run preview`),然后你可以在同一浏览器预览窗口中本地查看你网站的构建版本。 ¥When the build is finished, run the appropriate `preview` command (e.g. `npm run preview`) in your terminal and you can view the built version of your site locally in the same browser preview window. 请注意,这将预览上次运行构建命令时的代码。这旨在让你预览你的网站部署到网络时的外观。在构建后对代码所做的任何更改都不会在你预览网站时反映出来,直到你再次运行构建命令。 ¥Note that this previews your code as it existed when the build command was last run. This is meant to give you a preview of how your site will look when it is deployed to the web. Any later changes you make to your code after building will **not** be reflected while you preview your site until you run the build command again. 使用(`Ctrl` + `C`)退出预览并运行另一个终端命令,例如重新启动开发服务器以返回到 [在开发模式下工作](#work-in-development-mode),它会在你编辑时更新以显示代码更改的实时预览。 ¥Use (`Ctrl` + `C`) to quit the preview and run another terminal command, such as restarting the dev server to go back to [working in development mode](#work-in-development-mode) which does update as you edit to show a live preview of your code changes. Read more about [the Astro CLI](/en/reference/cli-reference/) and the terminal commands you will use as you build with Astro. Tip You may wish to [deploy your new site right away](/en/guides/deploy/), before you begin to add or change too much code. This is helpful to get a minimal, working version of your site published and can save you extra time and effort troubleshooting your deployment later. ## 下一步 [Section titled “下一步”](#下一步) ¥Next Steps 成功!现在你已准备好开始使用 Astro 进行构建!🥳 ¥Success! You are now ready to start building with Astro! 🥳 以下是我们建议接下来探索的一些内容。你可以按任何顺序阅读它们。你甚至可以暂时离开我们的文档,然后去玩新的 Astro 项目代码库,每当你遇到麻烦或有疑问时就回到这里。 ¥Here are a few things that we recommend exploring next. You can read them in any order. You can even leave our documentation for a bit and go play in your new Astro project codebase, coming back here whenever you run into trouble or have a question. ### 配置你的开发环境 [Section titled “配置你的开发环境”](#配置你的开发环境) ¥Configure your dev environment 浏览以下指南以定制你的开发体验。 ¥Explore the guides below to customize your development experience. [Editor Setup ](/en/editor-setup/)Customize your code editor to improve the Astro developer experience and unlock new features. [Dev Toolbar ](/en/guides/dev-toolbar/)Explore the helpful features of the dev toolbar. [TypeScript Configuration ](/en/guides/typescript/)Configure options for type-checking, IntelliSense, and more. ### 探索 Astro 的功能 [Section titled “探索 Astro 的功能”](#探索-astro-的功能) ¥Explore Astro’s Features [Understand your codebase ](/en/basics/project-structure/)Learn about Astro’s file structure in our Project Structure guide. [Create content collections ](/en/guides/content-collections/)Add content to your new site with frontmatter validation and automatic type-safety. [Add view transitions ](/en/guides/view-transitions/)Create seamless page transitions and animations. [Learn about Islands ](/en/concepts/islands/)Read about Astro's islands architecture. ### 参加入门教程 [Section titled “参加入门教程”](#参加入门教程) ¥Take the introductory tutorial 从我们的 [入门教程](/en/tutorial/0-introduction/) 中的一个空白页开始构建一个功能齐全的 Astro 博客。 ¥Build a fully functional Astro blog starting from a single blank page in our [introductory tutorial](/en/tutorial/0-introduction/). 这是了解 Astro 工作原理的好方法,并引导你了解页面、布局、组件、路由、群岛等的基础知识。它还包括一个可选的、适合初学者的单元,适合那些对一般 Web 开发概念较新的人,它将指导你在计算机上安装必要的应用、创建 GitHub 账户以及部署你的网站。 ¥This is a great way to see how Astro works and walks you through the basics of pages, layouts, components, routing, islands, and more. It also includes an optional, beginner-friendly unit for those newer to web development concepts in general, which will guide you through installing the necessary applications on your computer, creating a GitHub account, and deploying your site. # 配置概述 > 了解配置和自定义新项目和开发体验的方法。 Astro 是一个灵活、不有态度的框架,允许你以多种不同的方式配置你的项目。这意味着开始一个新项目可能会让人感到不知所措:没有 “一种最佳方式” 来设置你的 Astro 项目! ¥Astro is a flexible, unopinionated framework that allows you to configure your project in many different ways. This means that getting started with a new project might feel overwhelming: there is no “one best way” to set up your Astro project! 本 “配置” 部分中的指南将帮助你熟悉允许你配置和自定义项目和开发环境方面的各种文件。 ¥The guides in this “Configuration” section will help you familiarize yourself with the various files that allow you to configure and customize aspects of your project and development environment. 如果这是你的第一个 Astro 项目,或者你已经有一段时间没有设置新项目了,请使用以下指南和文档中的参考资料寻求帮助。 ¥If this is your first Astro project, or if it’s been a while since you’ve set up a new project, use the following guides and reference in the documentation for assistance. ## Astro 配置文件 [Section titled “Astro 配置文件”](#astro-配置文件) ¥The Astro config File [Astro 配置文件](/en/reference/configuration-reference/) 是包含在每个启动项目根目录中的 JavaScript 文件: ¥The [Astro config file](/en/reference/configuration-reference/) is a JavaScript file included at the root of every starter project: astro.config.mjs ```js import { defineConfig } from "astro/config"; export default defineConfig({ // your configuration options here... }); ``` 只有在你需要配置某些内容时才需要它,但大多数项目都会使用此文件。`defineConfig()` 助手在你的 IDE 中提供自动 IntelliSense,你可以在其中添加所有配置选项以告诉 Astro 如何构建和渲染你的项目为 HTML。 ¥It is only required if you have something to configure, but most projects will use this file. The `defineConfig()` helper provides automatic IntelliSense in your IDE and is where you will add all your configuration options to tell Astro how to build and render your project to HTML. 我们建议在大多数情况下使用默认文件格式 `.mjs`,或者如果你想在配置文件中编写 TypeScript,则使用 `.ts`。但是,`astro.config.js` 和 `astro.config.cjs` 也受支持。 ¥We recommend using the default file format `.mjs` in most cases, or `.ts` if you want to write TypeScript in your config file. However, `astro.config.js` and `astro.config.cjs` are also supported. Read Astro’s [configuration reference](/en/reference/configuration-reference/) for a full overview of all supported configuration options. ## TypeScript 配置文件 [Section titled “TypeScript 配置文件”](#typescript-配置文件) ¥The TypeScript config File 每个 Astro 入门项目都在你的项目中包含一个 `tsconfig.json` 文件。Astro 的 [组件脚本](/en/basics/astro-components/#the-component-script) 是 Typescript,它提供了 Astro 的编辑器工具,并允许你选择性地将语法添加到 JavaScript 中,以便对自己的项目代码进行类型检查。 ¥Every Astro starter project includes a `tsconfig.json` file in your project. Astro’s [component script](/en/basics/astro-components/#the-component-script) is Typescript, which provides Astro’s editor tooling and allows you to optionally add syntax to your JavaScript for type checking of your own project code. 使用 `tsconfig.json` 文件配置 TypeScript 模板,该模板将对你的代码执行类型检查、配置 TypeScript 插件、设置导入别名等。 ¥Use the `tsconfig.json` file to configure the TypeScript template that will perform type checks on your code, configure TypeScript plugins, set import aliases, and more. Read Astro’s [TypeScript guide](/en/guides/typescript/) for a full overview of TypeScript options and Astro’s built-in utility types. ## 开发体验 [Section titled “开发体验”](#开发体验) ¥Development Experience 在开发模式下工作时,你可以利用代码编辑器和其他工具来改善 Astro 开发者体验。 ¥While you work in development mode, you can take advantage of your code editor and other tools to improve the Astro developer experience. Astro 提供了自己的官方 VS Code 扩展,并与其他几种流行的编辑器工具兼容。Astro 还提供了一个可自定义的工具栏,可在开发服务器运行时显示在浏览器预览中。你可以安装甚至构建自己的工具栏应用以获得更多功能。 ¥Astro provides its own official VS Code extension and is compatible with several other popular editor tools. Astro also provides a customizable toolbar that displays in your browser preview while the dev server is running. You can install and even build your own toolbar apps for additional functionality. Read Astro’s guides to [editor setup options](/en/editor-setup/) and [using the dev toolbar](/en/guides/dev-toolbar/) to learn how to customize your development experience. ## 常见的新项目任务 [Section titled “常见的新项目任务”](#常见的新项目任务) ¥Common new project tasks 以下是你可能选择在新的 Astro 项目中采取的一些初始步骤。 ¥Here are some first steps you might choose to take with a new Astro project. ### 添加你的部署域 [Section titled “添加你的部署域”](#添加你的部署域) ¥Add your deployment domain 要生成站点地图并创建规范 URL,请在 [`site`](/en/reference/configuration-reference/#site) 选项中配置部署 URL。如果你要部署到路径(例如 `www.example.com/docs`),你还可以为项目的根目录配置 [`base`](/en/reference/configuration-reference/#base)。 ¥For generating your sitemap and creating canonical URLs, configure your deployment URL in the [`site`](/en/reference/configuration-reference/#site) option. If you are deploying to a path (e.g. `www.example.com/docs`), you can also configure a [`base`](/en/reference/configuration-reference/#base) for the root of your project. 此外,不同的部署主机可能对 URL 末尾的尾部斜杠有不同的行为。(例如 `example.com/about` 与 `example.com/about/`)。一旦你的站点部署完毕,你可能需要配置你的 [`trailingSlash`](/en/reference/configuration-reference/#trailingslash) 首选项。 ¥Additionally, different deployment hosts may have different behavior regarding trailing slashes at the end of your URLs. (e.g. `example.com/about` vs `example.com/about/`). Once your site is deployed, you may need to configure your [`trailingSlash`](/en/reference/configuration-reference/#trailingslash) preference. astro.config.mjs ```js import { defineConfig } from "astro/config"; export default defineConfig({ site: "https://www.example.com", base: "/docs", trailingSlash: "always", }); ``` ### 添加网站元数据 [Section titled “添加网站元数据”](#添加网站元数据) ¥Add site metadata Astro 不会将其配置文件用于常见的 SEO 或元数据,仅用于构建项目代码并将其渲染为 HTML 所需的信息。 ¥Astro does not use its configuration file for common SEO or meta data, only for information required to build your project code and render it to HTML. 相反,这些信息会使用标准 HTML `` 和 `` 标签添加到你的页面 ``,就像你编写纯 HTML 页面一样。 ¥Instead, this information is added to your page `` using standard HTML `` and `` tags, just as if you were writing plain HTML pages. Astro 网站的一个常见模式是创建一个 `` [`.astro` 组件](/en/basics/astro-components/),可以将其添加到通用 [布局组件](/en/basics/layouts/) 中,以便应用于所有页面。 ¥One common pattern for Astro sites is to create a `` [`.astro` component](/en/basics/astro-components/) that can be added to a common [layout component](/en/basics/layouts/) so it can apply to all your pages. src/components/MainLayout.astro ```astro --- import Head from "./Head.astro"; const { ...props } = Astro.props; --- ``` 因为 `Head.astro` 只是一个常规的 Astro 组件,所以你可以导入文件并接收从其他组件传递的 props,例如特定的页面标题。 ¥Because `Head.astro` is just a regular Astro component, you can import files and receive props passed from other components, such as a specific page title. src/components/Head.astro ```astro --- import Favicon from "../assets/Favicon.astro"; import SomeOtherTags from "./SomeOtherTags.astro"; const { title = "My Astro Website", ...props } = Astro.props; --- {title} ``` # Astro 课程 > 通过精彩的课程和教程学习 Astro。 想通过课程或教程开始学习 Astro 吗? ¥Want to get started learning Astro with a course or tutorial? 你可以使用我们的 [官方文档 创建博客教程](/en/tutorial/0-introduction/) 学习 Astro 的基础知识,或浏览我们推荐的 Astro 教育内容集合。 ¥You can learn the basics of Astro with our [official docs Build a Blog tutorial](/en/tutorial/0-introduction/), or explore our collection of recommended Astro educational content. ## 教育合作伙伴 [Section titled “教育合作伙伴”](#教育合作伙伴) ¥Education Partners Support Astro while you learn Use Astro’s affiliate links for discounts with our education partners and some of your purchase goes directly back to funding development of the Astro open source project! 通过视频课程、互动挑战和项目,向值得信赖的 Astro 讲师学习 Astro! ¥Learn Astro from trusted Astro educators, with video lessons, interactive challenges, and projects! [Learn Astro with Coding in Public ](https://learnastro.dev/?code=ASTRO_PROMO)A premium interactive course with 150+ video lessons that teaches you how to use Astro’s built-in tooling and features. [Learn Astro with James Q Quick ](https://scrimba.com/intro-to-astro-c00ar0fi5u?via=astro)Build your first Astro site with 35 interactive Scrimba lessons, with video and IDE merged into one unique learning platform. ## 社区学习资源 [Section titled “社区学习资源”](#社区学习资源) ¥Community learning resources 通过精选的指南、文章和博客文章,向你的宇航员同伴学习。 ¥Learn from your fellow astronauts with curated collections of guides, articles, and blog posts. [Astro Tips ](https://astro-tips.dev/)Advanced, unusual, experimental, and community-written recipes, tutorials, and quick tips. [Astro Support Squid ](https://get.supportsquid.ink/)An open, public Astro support forum and knowledge base outside of the Astro Discord. # 组件 > Astro 组件简介。 Astro 组件是任何 Astro 项目的基本构建块。它们是仅 HTML 的模板组件,没有客户端运行时,并使用 `.astro` 文件扩展名。 ¥**Astro components** are the basic building blocks of any Astro project. They are HTML-only templating components with no client-side runtime and use the `.astro` file extension. Note If you know HTML, you already know enough to write your first Astro component. Learn more in the [Astro syntax reference](/en/reference/astro-syntax/). Astro 组件非常灵活。Astro 组件可以小到 HTML 片段,就像一组常见的 `` 标签,使 SEO 易于使用。组件可以是可重复使用的 UI 元素,例如标题或配置文件卡。Astro 组件甚至可以包含整个页面布局,或者当位于特殊的 `src/pages/` 文件夹中时,它本身就是整个页面。 ¥Astro components are extremely flexible. An Astro component can be as small as a snippet of HTML, like a collection of common `` tags that make SEO easy to work with. Components can be reusable UI elements, like a header or a profile card. Astro components can even contain an entire page layout or, when located in the special `src/pages/` folder, be an entire page itself. 关于 Astro 组件,最重要的是要知道它们不会在客户端上渲染。它们在构建时或按需渲染为 HTML。你可以在组件 frontmatter 中包含 JavaScript 代码,所有这些代码都将从发送到用户浏览器的最终页面中删除。结果是网站速度更快,默认情况下添加的 JavaScript 占用量为零。 ¥The most important thing to know about Astro components is that they **don’t render on the client**. They render to HTML either at build-time or on-demand. You can include JavaScript code inside of your component frontmatter, and all of it will be stripped from the final page sent to your users’ browsers. The result is a faster site, with zero JavaScript footprint added by default. 当你的 Astro 组件确实需要客户端交互时,你可以将 [标准 HTML `
Target here
``` `.astro` 部分必须存在于相应的文件路径中,并且包含将页面定义为部分的导出: ¥The `.astro` partial must exist at the corresponding file path, and include an export defining the page as a partial: src/pages/partials/clicked.astro ```astro --- export const partial = true; ---
I was clicked!
``` 有关使用 htmx 的更多详细信息,请参阅 [htmx 文档](https://htmx.nodejs.cn/docs/)。 ¥See the [htmx documentation](https://htmx.nodejs.cn/docs/) for more details on using htmx. # 布局 > Astro 中布局简介。 布局用于提供可重复使用的 UI 结构,例如页面模板。 ¥**Layouts** are [Astro components](/en/basics/astro-components/) used to provide a reusable UI structure, such as a page template. 我们通常使用术语 “layout” 来表示 Astro 组件,这些组件提供跨页面共享的通用 UI 元素,例如页眉、导航栏和页脚。典型的 Astro 布局组件为 [Astro、Markdown 或 MDX 页面](/en/basics/astro-pages/) 提供: ¥We conventionally use the term “layout” for Astro components that provide common UI elements shared across pages such as headers, navigation bars, and footers. A typical Astro layout component provides [Astro, Markdown or MDX pages](/en/basics/astro-pages/) with: * 页面外壳(``、`` 和 `` 标签) * [**``**](/en/basics/astro-components/#slots) 指定应在何处注入各个页面内容。 但是,布局组件没有什么特别的!它们可以像任何其他 Astro 组件一样 [accept props](/en/basics/astro-components/#component-props) and [import and use other components](/en/basics/astro-components/#component-structure)。它们可以包括 [UI 框架组件](/en/guides/framework-components/) 和 [客户端脚本](/en/guides/client-side-scripts/)。它们甚至不必提供完整的页面 shell,而是可以用作部分 UI 模板。 ¥But, there is nothing special about a layout component! They can [accept props](/en/basics/astro-components/#component-props) and [import and use other components](/en/basics/astro-components/#component-structure) like any other Astro component. They can include [UI frameworks components](/en/guides/framework-components/) and [client-side scripts](/en/guides/client-side-scripts/). They do not even have to provide a full page shell, and can instead be used as partial UI templates. 但是,如果布局组件确实包含页面外壳,则其 `` 元素必须是组件中所有其他元素的父元素。 ¥However, if a layout component does contain a page shell, its `` element must be the parent of all other elements in the component. 布局组件通常放置在项目中的 `src/layouts` 目录中以便组织,但这不是必需的;你可以选择将它们放置在项目中的任何位置。你甚至可以通过 [在布局名称前添加 `_` 前缀](/en/guides/routing/#excluding-pages) 将布局组件与页面并置。 ¥Layout components are commonly placed in a `src/layouts` directory in your project for organization, but this is not a requirement; you can choose to place them anywhere in your project. You can even colocate layout components alongside your pages by [prefixing the layout names with `_`](/en/guides/routing/#excluding-pages). ## 布局示例 [Section titled “布局示例”](#布局示例) ¥Sample Layout src/layouts/MySiteLayout.astro ```astro --- import BaseHead from '../components/BaseHead.astro'; import Footer from '../components/Footer.astro'; const { title } = Astro.props; ---

{title}