diff --git a/netlify.toml b/netlify.toml
index 0843f1dfac07a..e4174d26a996d 100644
--- a/netlify.toml
+++ b/netlify.toml
@@ -83,6 +83,14 @@
from = "/:lang/guides/client-side-routing"
to = "/:lang/guides/view-transitions"
+ [[redirects]]
+ from = "/:lang/guides/assets"
+ to = "/:lang/guides/images"
+
+ [[redirects]]
+ from = "/:lang/guides/integrations-guide/image"
+ to = "/:lang/guides/images"
+
[[redirects]]
from = "/:lang/migration/0.21.0"
to = "/:lang/guides/upgrade-to/v1"
diff --git a/src/content/docs/de/guides/images.mdx b/old-translations/de/guides/images.mdx
similarity index 99%
rename from src/content/docs/de/guides/images.mdx
rename to old-translations/de/guides/images.mdx
index e561b6b44b20c..693194dc9210e 100644
--- a/src/content/docs/de/guides/images.mdx
+++ b/old-translations/de/guides/images.mdx
@@ -9,7 +9,7 @@ import Since from '~/components/Since.astro';
Astro bietet dir verschiedene Möglichkeiten, Bilder auf deiner Website zu verwenden, ganz gleich, ob sie lokal in deinem Projekt gespeichert sind, auf anderen Quellen verlinkt werden oder in einem CMS oder CDN gespeichert sind!
:::note[Assets verwenden (Experimentell)]
-Die experimentelle Asset-Unterstützung wurde in `astro@2.1.0` hinzugefügt. Wenn du die Unterstützung für Assets aktiviert hast, findest du weitere Informationen in der [Asset-Anleitung (Experimentell)](/de/guides/assets/).
+Die experimentelle Asset-Unterstützung wurde in `astro@2.1.0` hinzugefügt. Wenn du die Unterstützung für Assets aktiviert hast, findest du weitere Informationen in der [Asset-Anleitung (Experimentell)](/de/guides/images/).
**Einige der folgenden Ratschläge sind nicht mit der experimentellen Flag kompatibel.**
:::
@@ -38,7 +38,7 @@ import rocket from '../images/rocket.svg';
Du kannst die Standard Markdown `![]()` Syntax oder die Standard HTML ``-Tags in deinen `.md`-Dateien für Bilder verwenden, die sich in deinem `public/`-Ordner befinden, oder für Remote-Bilder auf einem anderen Server.
-Wenn du deine Bilder nicht in `public/` speichern kannst, empfehlen wir, die [experimentelle Unterstützung für Assets](/de/guides/assets/) zu aktivieren oder das Dateiformat `.mdx` zu verwenden, mit dem du importierte Komponenten mit einer Markdown-ähnlichen Syntax kombinieren kannst. Verwende die [MDX-Integration](/de/guides/integrations-guide/mdx/), um Astro-Unterstützung für MDX hinzuzufügen.
+Wenn du deine Bilder nicht in `public/` speichern kannst, empfehlen wir, die [experimentelle Unterstützung für Assets](/de/guides/images/) zu aktivieren oder das Dateiformat `.mdx` zu verwenden, mit dem du importierte Komponenten mit einer Markdown-ähnlichen Syntax kombinieren kannst. Verwende die [MDX-Integration](/de/guides/integrations-guide/mdx/), um Astro-Unterstützung für MDX hinzuzufügen.
```md
@@ -121,7 +121,7 @@ Das Attribut `src` ist **relativ zum öffentlichen Ordner**. In Markdown kannst
### `src/assets/` (experimentell)
-In der Anleitung [Assets (Experimentell)](/de/guides/assets/) kannst du nachlesen, wie du den Ordner `/assets/` experimentell nutzen kannst.
+In der Anleitung [Assets (Experimentell)](/de/guides/images/) kannst du nachlesen, wie du den Ordner `/assets/` experimentell nutzen kannst.
Dazu musst du deine bestehenden Bilder aktualisieren, die aktuelle Astro-Bildintegration entfernen und zusätzliche manuelle Änderungen vornehmen, um einige der neuen Funktionen zu nutzen.
@@ -132,7 +132,7 @@ Die offizielle Bild-Integration von Astro bietet zwei verschiedene Astro-Kompone
Nach der [Installation von `@astrojs/image`](/de/guides/integrations-guide/image/#installation) kannst du diese beiden Komponenten überall dort verwenden, wo du Astro-Komponenten verwenden kannst: in `.astro`- und `.mdx`-Dateien.
:::note[Inkompatibel mit Assets]
-Wenn du die experimentelle Asset-Unterstützung aktiviert hast, musst du die offizielle Integration deinstallieren. Weitere Informationen findest du im [Assets (Experimental) Guide](/de/guides/assets/).
+Wenn du die experimentelle Asset-Unterstützung aktiviert hast, musst du die offizielle Integration deinstallieren. Weitere Informationen findest du im [Assets (Experimental) Guide](/de/guides/images/).
:::
### ``
diff --git a/src/content/docs/fr/guides/images.mdx b/old-translations/fr/images.mdx
similarity index 100%
rename from src/content/docs/fr/guides/images.mdx
rename to old-translations/fr/images.mdx
diff --git a/old-translations/ja/images.mdx b/old-translations/ja/images.mdx
new file mode 100644
index 0000000000000..54c53602c96e2
--- /dev/null
+++ b/old-translations/ja/images.mdx
@@ -0,0 +1,373 @@
+---
+title: 画像
+description: Astroでの画像の取り扱いを学びます
+i18nReady: true
+---
+import Since from '~/components/Since.astro';
+
+Astroは、プロジェクト内に保存されている画像やリモート上にリンクされている画像、CMSやCDNに保存されている画像をサイト上で表示するために様々な手段を提供しています。
+
+:::note[アセットの活用 (実験的)]
+実験的なアセットサポートが`astro@2.1.0`に追加されました。アセットサポートを有効にした場合、追加情報については [アセット (実験的) ガイド](/ja/guides/images/) を参照してください。
+
+**以下のアドバイスの中には、アセットのフラグを有効にした場合に互換性がなくなるものもあります。**
+:::
+
+
+### `.astro`ファイル内
+
+astroでは``要素を使って画像を表示でき、HTML画像属性をすべてサポートしています。
+
+`src` 属性は必須で、その書式は画像の保存場所や、アセットの実験的なサポートを有効にしているかどうかによって異なります:
+
+```astro title="src/pages/index.astro"
+---
+import rocket from '../images/rocket.svg';
+---
+
+
+
+
+
+
+
+
+```
+
+### Markdownファイル内
+
+`.md`ファイル内では標準的な`![]()`構文や``タグを記載することで`public/`フォルダや、他サーバー上にあるリモート画像を表示できます。
+
+もし`public/`に画像を保存できない場合、[アセットの実験的なサポート](/ja/guides/images/)を有効にするか、インポートされたコンポーネントをMarkdownのような構文と組み合わせて使える`.mdx`ファイルフォーマットを利用することをお勧めします。AstroにMDXのサポートを追加するには[MDX インテグレーション](/ja/guides/integrations-guide/mdx/)を利用します。
+
+```md
+
+
+# Markdownページ
+
+
+
+
+
+
+
+
+```
+
+### MDXファイル内
+
+`.mdx`ファイル内では標準的なMarkdown文法`![]()`やJSXの``タグを使って`public/`フォルダーやリモートサーバーの画像を表示できます。
+
+加えて、Astroコンポーネントのようにプロジェクトの`src/`ディレクトリに保存されている画像をインポートして利用できます。
+
+```mdx title="src/pages/post-1.mdx"
+
+import rocket from '../images/rocket.svg';
+
+# MDXページ
+
+// src/images/rocket.svgに保存されたローカル画像
+
+
+// public/assets/stars.pngに保存されたローカル画像
+
+
+
+// 他サーバー上にあるリモート画像
+
+
+```
+
+### UIフレームワークコンポーネント内
+
+[UIフレームコンポーネント](/ja/core-concepts/framework-components/)(ReactやSvelteなど)に画像を追加する場合、そのコンポーネントのフレームワークに沿った画像の構文を利用します。
+
+## 画像の保存場所
+
+### `src/`
+
+`src`に保存された画像は、コンポーネント(`.astro`や`.mdx`、そして他のUIフレームワーク)から利用できますが、Markdownファイルからは利用できません。
+
+Markdownファイルを利用する必要がある場合、[`public/`へ配置する](#public)か[CMSやCDN上の画像を利用](#cmsやcdn上の画像利用)することをお勧めします。
+
+画像を**相対ファイルパス**または[importエイリアス](/ja/guides/aliases/)を利用してコンポーネントファイル内でインポートし、画像の`src`属性として利用できます。
+
+
+```astro
+---
+// src/pages/index.astro
+
+// `src/images/`内の画像へアクセスします。
+import logo from '../images/logo.png';
+---
+
+```
+
+### `public/`
+
+`public/`に保存された画像はコンポーネント(`.astro`や`.mdx`、そして他のUIフレームワーク)とMarkdownファイルからも利用できます。
+
+しかし、`/public`ディレクトリにあるファイルは処理されずにそのまま提供、コピーされます。Markdownファイル以外で画像を利用する場合はAstroが画像を変換・最適化・バンドルできるように、可能な限りローカル画像は`src`に保存するのをお勧めします。
+
+`src`属性は**publicフォルダからの相対パス**です。Markdownでは`![]()`の表記を利用できます。
+
+```astro title="src/pages/index.astro"
+---
+// `public/images/`内の画像へアクセスします。
+---
+
+```
+
+### `src/assets/` (実験的)
+
+`/assets/` フォルダの実験的な使用を有効にするには、[アセット(実験的)](/ja/guides/images/)ガイドを参照してください。
+
+その場合、既存の画像を更新し、現在のAstro画像インテグレーションを削除する必要があります。また、Astroの新機能の一部を利用するためには、さらに手動での変更が必要になります。
+
+## Astro画像インテグレーション
+
+Astro公式の画像のインテグレーションは、最適化された画像をレンダリングするためのAstroコンポーネント``と``を提供しています。これらのコンポーネントは全ての静的サイトと、[一部のサーバーサイドレンダリングのデプロイホスト](/ja/guides/integrations-guide/image/#installation)をサポートしています。
+
+[`@astrojs/image`のインストール](/ja/guides/integrations-guide/image/#installation)で、`.astro`と`.mdx`などのAstroコンポーネントを利用できるファイル内でこの2つのコンポーネントを利用できます。
+
+:::note[アセットの互換性がない]
+アセットの実験的なサポートを有効にしている場合は、公式インテグレーションをアンインストールする必要があります。詳細については、[アセット (実験的) ガイド](/ja/guides/images/) を参照してください。
+:::
+
+### ``
+
+Astroの[``コンポーネント](/ja/guides/integrations-guide/image/#image-)は1つの画像を最適化し、幅・高さ・アスペクト比を指定できます。また特定の出力フォーマットに画像を変換できます。
+
+このコンポーネントはディスプレイ間で一貫したサイズを維持したい画像や、画質を厳密にコントロールしたいもの(ロゴなど)に有効です。
+
+レスポンシブ画像の場合やアートディレクションの場合は、代わりに``コンポーネントを利用します。
+
+#### リモート画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt)・[`format`](/ja/guides/integrations-guide/image/#format)・サイズ)
+
+``コンポーネントの`src`属性に完全なURLを渡し、`alt`の値を含めます。
+
+``コンポーネントはリモート画像のオリジナルのファイルフォーマットを検知できないため、リモート画像を変換するために出力する`format`(pngやavifなど)を指定する必要があります。
+
+``コンポーネントはリモート画像のサイズを認識しないので、コンテンツレイアウトのシフトを回避するために[`width`](/ja/guides/integrations-guide/image/#width)と[`height`](/ja/guides/integrations-guide/image/#height)、またはどちらか1つのサイズと[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio)を指定する必要があります。
+
+[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションです。
+
+#### `src/`のローカル画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt))
+
+フロントマターで画像をインポートして、``コンポーネントの`src`属性へ直接渡します。
+
+`alt`は必須ですが[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションで、指定が無ければ画像ファイルのプロパティがデフォルト値として設定されます。
+
+#### `public/`のローカル画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt)・[`format`](/ja/guides/integrations-guide/image/#format)・サイズ)
+
+コンポーネントの`src`属性に公開フォルダからの相対パスを渡し、`alt`に値を含めます。
+
+これはリモート画像として扱われ、[`width`](/ja/guides/integrations-guide/image/#width)と[`height`](/ja/guides/integrations-guide/image/#height)の両方の属性か、またはどちらか1つのサイズと[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio)属性が必須です。
+
+画像を変換するための`format`属性値が必要です。(pngやavifなど)
+
+[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションです。
+
+元画像は`public/`にある他のファイルと同じくビルドフォルダーにそのままコピーされ、Astroの画像インテグレーションは最適化された画像を返します。
+
+#### 例
+
+```astro
+---
+// src/pages/index.astro
+import { Image } from '@astrojs/image/components';
+import localImage from "../assets/logo.png";
+const remoteImage = "https://picsum.photos/id/957/300/200.jpg";
+const localAlt = "The Astro Logo";
+const remoteAlt = "A low-angle view of a forest during the daytime";
+---
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+### ` `
+
+Astroの[``コンポーネント](/ja/guides/integrations-guide/image/#picture-)は複数の画像サイズ・フォーマット・レイアウトなど、サイト上でレスポンシブな画像を提供するために利用できます。
+
+画面サイズや帯域幅に基づいて、画像に最適なサイズ、解像度、ファイルタイプを利用ユーザーのブラウザに任せることができます。また、メディアクエリに基づいてブラウザに従わせるルールを指定できます。
+
+このコンポーネントは、ユーザーが様々な画面サイズで見る画像を最適化するためや、アートディレクションに最適です。
+
+:::tip
+[レスポンシブ画像とアートディレクション](https://developer.mozilla.org/ja/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#%E3%82%A2%E3%83%BC%E3%83%88%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3)の詳細はMDNのガイドを参照してください。
+:::
+
+#### リモート画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1)・[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio-1))
+
+完全なURLを``コンポーネントの`src`属性へ渡します。
+
+またビルド時に正しい高さを計算できるようにリモート画像は`aspectRatio`も必要になります。
+
+画像の幅と画面サイズに関する指示をコンポーネントに与える必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+
+[`formats`](/ja/guides/integrations-guide/image/#formats)は必須ではありませんが、リモート画像の元のフォーマットが不明となりデフォルト値は含まれません。何も指定が無ければ、`webp`と`avif`だけが含まれます。
+
+#### ローカル画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1))
+
+フロントマターで画像をインポートして、``コンポーネントの`src`属性へ直接渡します。
+
+画像の幅と画像のガイダンスをコンポーネントへ渡す必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+
+``コンポーネントの[`formats`](/ja/guides/integrations-guide/image/#formats)に指定がなければ、デフォルト値は元の画像のフォーマットに加えて`avif`と`webp`が含まれます。
+
+#### `public/`の画像
+
+(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1)・[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio-1))
+
+コンポーネントの`src`属性にはpublicフォルダからの相対パスを渡し、`alt`の値を必要とします。
+
+画像はリモート画像として扱われるため、ビルド時に正しい高さを計算できるように`aspectRatio`の指定が必要です。
+
+画像の幅と画面サイズに関する指示をコンポーネントに与える必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+
+[`formats`](/ja/guides/integrations-guide/image/#formats)は必須ではありませんが、`public/`フォルダにある画像の元のフォーマットが不明となりデフォルト値は含まれません。何も指定が無ければ、`webp`と`avif`だけが含まれます。
+
+元の画像は`public/`にある他のファイルと同じくビルドフォルダーにそのままコピーされ、Astroの画像インテグレーションは最適化された画像を返します。
+
+#### 例
+
+```astro
+---
+import { Picture } from '@astrojs/image/components';
+import localImage from '../assets/logo.png';
+const remoteImage = 'https://docs.astro.build/assets/full-logo-light.png';
+---
+
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+### MDXでの利用
+
+`.mdx`ファイル内では、インポートとエクスポートを通して``と``が画像の`src`を受け取ることができます。
+
+```mdx
+// src/pages/index.mdx
+
+import { Image, Picture } from '@astrojs/image/components';
+import rocket from '../assets/rocket.png';
+export const logo = 'https://docs.astro.build/assets/full-logo-light.png';
+
+
+
+
+
+```
+
+### デフォルト値を設定する
+
+現在、``と``コンポーネントにデフォルト値を指定する方法はありません。必須属性はそれぞれのコンポーネントに設定する必要があります。
+
+代わりの方法として、再利用できるよう他のAstroコンポーネントでこれらのコンポーネントをラッピングできます。例えば、以下のようにブログ記事画像をコンポーネントとして作成できます。
+
+```astro title="src/components/BlogPostImage.astro"
+---
+import { Picture } from '@astrojs/image/components';
+
+const {src, ...attrs} = Astro.props;
+---
+
+
+
+```
+
+### 画像インテグレーションで``を使う
+
+公式の画像インテグレーションにより、画像のインポートはソース文字列ではなくオブジェクトを返すように変更されます。このオブジェクトは、インポートされたファイルから派生した以下のプロパティを持ちます。
+```ts
+{
+ src: string;
+ width: number;
+ height: number;
+ format: 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp';
+}
+```
+
+画像インテグレーションがインストールされている場合は、``を使用する際にオブジェクトの`src`プロパティを参照してください。
+
+```astro ".src"
+---
+import rocket from '../images/rocket.svg';
+---
+
+```
+
+あるいは、インポートに`?url`を追加して、ソース文字列を返すように指示する。
+
+```astro "?url"
+---
+import rocket from '../images/rocket.svg?url';
+---
+
+```
+
+## CMSやCDN上の画像利用
+
+CDNネットワーク上の画像をAstroで利用するには、画像の完全なURLを``タグやMarkdownの`src`属性として利用します。
+
+代わりに、もしCDNがNode.js SDKを提供している場合はプロジェクトでSDKを利用できます。例えば、[CloudinaryのSDK](https://cloudinary.com/documentation/node_integration)は適切な`src`を利用して``タグを生成できます。
+
+Astroの画像インテグレーションの[``を用いた外部画像](#リモート画像)や[``](#リモート画像-1)コンポーネントを利用するには、リモート画像を扱うための適切なサイズとフォーマットを指定する必要があります。
+
+## Altテキスト
+
+画像が誰も同じように見えるわけではないため、画像を扱う上でアクセシビリティは特に重要になります。`alt`属性は画像に[Altテキストによる記述](https://www.w3.org/WAI/tutorials/images/)を与えます。
+
+この属性は画像インテグレーションの``と``コンポーネントには必須です。Altテキストが指定されていない場合これらのコンポーネントはエラーを投げます。
+
+画像が単なる飾り(ページの理解に貢献しない画像)の場合、スクリーンリーダーが画像を無視するように`alt=""`を設定します。
+
+## コミュニテーインテグレーション
+
+公式の[`@astrojs/image`](/ja/guides/integrations-guide/image/)インテグレーションに加え、Astroプロジェクトで画像の最適化や処理を行うためのサードパーティー製の[コミュニティー画像インテグレーション](https://astro.build/integrations?search=images)がいくつかあります。
diff --git a/old-translations/zh-CN/guides/images.mdx b/old-translations/zh-CN/guides/images.mdx
new file mode 100644
index 0000000000000..a71300741771a
--- /dev/null
+++ b/old-translations/zh-CN/guides/images.mdx
@@ -0,0 +1,163 @@
+---
+title: 图片
+description: 学习如何在 Astro 项目中包含图片。
+i18nReady: true
+---
+import Since from '~/components/Since.astro';
+
+
+在 Astro 项目中,有很多种在网站中使用图片的方式。无论是用存储在项目中的图片,还是链接外部图片,亦或从像 CMS(内容管理系统)或 CDN(内容分发网络)这样的地方加载图片,都没问题!
+
+:::note[`astro:assets` (Experimental - coming in v3.0)]
+实验性 `astro:assets` 模块将在 `astro@3.0` 中默认启用.
+
+请按照 [资源(实验性)使用指南](/zh-cn/guides/images/) 开始使用新的图片解决方案!
+
+**下面的一些建议可能与实验性标志不兼容。如果你正在使用 `astro:assets` 请参考资源页面。**
+:::
+
+### 在 `.astro` 文件中
+
+你可以在 `.astro` 文件中使用标准的 HTML `` 或 `` 元素来展示图片,同时也支持所有 HTML 图片属性。
+
+src 属性是必需的,其格式取决于图像的存储位置以及你是否启用了对资源的实验性支持:
+
+```astro
+---
+// src/pages/index.astro
+import rocket from '../images/rocket.svg';
+---
+
+
+
+
+
+
+
+
+```
+
+### 在 Markdown 文件中
+
+可以在 `.md` 文件中使用 Markdown 标准语法 `![]()`,或 HTML 标准语法 `` 标签,来调用位于 `public/` 文件夹下或其它服务器上的图片。
+
+如果你无法将图片保留在 `public/` 中,我们建议启用 [资源的实验性支持](/zh-cn/guides/images/), 或使用 `.mdx` 文件格式,该格式允许你将导入的组件与类似 Markdown 的语法结合起来。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 向 Astro 添加对 MDX 的支持。
+```md
+
+
+# 我的 Markdown 页面
+
+
+
+
+
+
+
+
+```
+
+### 在 MDX 文件中
+
+你可以在 .mdx 文件中使用标准 Markdown `![]()` 语法或 JSX 的 `` 标签来显示 `public/ ` 文件夹或远程服务器中的图片。
+
+此外,你也可以导入和使用位于项目 `src/` 目录中的图像,就像在 Astro 组件中一样。
+
+
+```mdx title="src/pages/post-1.mdx"
+
+import rocket from '../images/rocket.svg';
+
+# My MDX Page
+
+// 存放在项目中 src/images/rocket.svg 路径的图片
+
+
+// 存放在项目中 public/assets/stars.png 路径的图片
+
+
+
+// 位于其它服务器上的图片
+
+
+```
+
+### UI 框架中的组件
+
+当在 [UI 框架组件](/zh-cn/core-concepts/framework-components/)(例如 React、Svelte)中添加图像时,请使用适合该框架的图像语法。
+
+
+
+## 存放图片的位置
+
+### `src/`
+
+存储在 `src/`中的图像可以由组件(`.astro`,`.mdx`和其他 UI 框架)使用,但不能在 Markdown 文档中使用。
+
+如果您必须使用 Markdown 文档,我们建议你将图像保存在 ['public/'](#public) 中或 [远程](#使用-cms-或-cdn-上的图片) 存储他们。
+
+从任何组件文档中的 **相对文档路径** 或 [导入别名](/zh-cn/guides/aliases/) 导入它们,然后像使用 `src`属性一样使用。
+
+```astro
+---
+// src/pages/index.astro
+
+// Access images in `src/images/`
+import logo from '../images/logo.png';
+---
+
+```
+
+### `public/`
+
+存储在 `public/` 中的图像可以被组件(`.astro`,`.mdx`和其他UI框架)和Markdown文档使用。
+
+然而,位于 `/public` 目录中的文件始终按原样提供或复制,不进行任何处理。如果你在 Markdown 文件之外使用图像,我们建议尽可能将本地图像保存在 `src/` 中,以便 Astro 对其进行转换、优化和打包。
+
+`src` 属性是 **相对于 public 文件夹的**。在 Markdown 中,你可以使用 `![]()` 表示。
+
+```astro
+---
+// src/pages/index.astro
+
+// 存取放在 `public/images/` 里的图片
+---
+
+```
+
+### `src/assets/` (实验性)
+
+请参阅 [资源(实验性)](/zh-cn/guides/images/) 指南,了解如何启用 `/assets/` 文件夹的实验性用法。
+
+这将需要你更新现有图片,删除当前的 Astro 图片集成,并且还需要额外的手动更改以利用其某些新功能。
+
+## Astro 的图片集成
+
+:::note[将在 v3.0 中弃用]
+Astro v3 将不再主动支持 [`@astrojs/image`](https://github.com/withastro/astro/tree/main/packages/integrations/image) 集成
+
+我们建议你尽早删除它,并使用将内置在 `astro@3.0` 中的实验性 `astro:assets` 模块。
+
+请按照 [资源(实验性)使用指南](/zh-cn/guides/images/) 开始使用新的图片解决方案!
+
+**`astro:assets` 目前还不能完全替代 `@astrojs/image` ,但它正在被积极开发中。**
+:::
+
+有关在 Astro v2 中使用 `@astrojs/image` 的文档,请参阅 [`@astrojs/image` 文档](https://github.com/withastro/astro/blob/main/packages/integrations/image/README.md)
+
+## 使用 CMS 或 CDN 上的图片
+
+Image CDN 可与 Astro 配合使用,可将图片的完整网址作为 `` 标签中的 `src` 属性或 Markdown 标记
+
+如果 CDN 提供了 Node.js SDK ,则可以在项目中使用它。例如,[Cloudinary 的 SDK](https://cloudinary.com/documentation/node_integration) 可以生成带有相应 `src` 属性 的 ` ` 标签。
+
+## Alt Text
+
+并非所有用户都能以相同的方式查看图片,因此在使用图片时可访问性是一个特别重要的问题。使用 `alt` 属性为图片提供 [描述性替代文本](https://www.w3.org/WAI/tutorials/images/)。
+
+此属性对于映像集成的 `` 和 `` 组件是必需的,如果未提供替代文本,这些组件将引发错误。
+
+如果图像只是装饰性的(即无助于理解页面)请设置 `alt=""`,以便屏幕阅读器知道忽略该图像。
+
+## 社区开发的集成
+
+除了官方的 [`@astrojs/image`](/zh-cn/guides/integrations-guid/image/) 集成外,社区还开发了[社区图片集成](https://astro.build/integrations?search=images),用于处理和优化 Astro 项目中的图片。
diff --git a/src/content/docs/ar/core-concepts/astro-components.mdx b/src/content/docs/ar/core-concepts/astro-components.mdx
index f980a01ee1565..a1de3495cf2ed 100644
--- a/src/content/docs/ar/core-concepts/astro-components.mdx
+++ b/src/content/docs/ar/core-concepts/astro-components.mdx
@@ -286,7 +286,7 @@ const { title } = Astro.props
- لا يدعمون frontmatter، أو الإستيراد على جانب الخادم (Server-side imports)، أو التعابير الديناميكية.
- أي وسوم `
+
+
-```astro title="src/pages/index.astro"
----
-// Access images in `public/images/`
----
-
```
-### `src/assets/` (experimental)
+#### Passing the Image component
-See the [Assets (Experimental)](/en/guides/assets/) guide for enabling experimental use of the `/assets/` folder.
+The `` component, like any other Astro component, **is unavailable to UI framework components**.
-This will require you to update your existing images, remove the current Astro image integration, and will also require additional manual changes to take advantage of some of its new features.
+But, you can pass the static content generated by `` to a framework component inside a `.astro` file as children or using a [named ``](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components):
-## Astro's Image Integration
-:::note[to be deprecated in v3.0]
-The [`@astrojs/image`](https://github.com/withastro/astro/tree/main/packages/integrations/image) integration will no longer be actively supported in Astro v3.0.
+```astro title="ImageWrapper.astro"
+---
+import ReactComponent from './ReactComponent.jsx';
+import { Image } from "astro:assets"
+import stars from "~/stars/docline.png";
+---
-We suggest removing it at your earliest convenience and using the experimental `astro:assets` module which will be built in to `astro@3.0`.
+
+
+
+```
-Follow the [Assets (Experimental) Guide](/en/guides/assets/) to start using Astro's new image solution today!
+## Generating images with `getImage()`
-**`astro:assets` is not a complete replacement for `@astrojs/image` at this time, but it is under active development.**
+:::caution
+`getImage()` relies on server-only APIs and breaks the build when used on the client.
:::
-For documentation on using `@astrojs/image` in Astro v2, please see the [`@astrojs/image` package documentation](https://github.com/withastro/astro/blob/main/packages/integrations/image/README.md)
+The `getImage()` function is intended for generating images destined to be used somewhere else than directly in HTML, for example in an [API Route](/en/core-concepts/endpoints/#server-endpoints-api-routes). It also allows you to create your own custom `` component.
-## Using Images from a CMS or CDN
+`getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`).
-Image CDNs work with Astro. Use an image's full URL as the `src` attribute in an `` tag or Markdown notation.
+```astro
+---
+import { getImage } from "astro:assets";
+import myBackground from "../background.png"
+
+const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
+---
+
+
+```
-Alternatively, if the CDN provides a Node.js SDK, you can use that in your project. For example, [Cloudinary’s SDK](https://cloudinary.com/documentation/node_integration) can generate the `` tag with the appropriate `src` for you.
+It returns an object with the following properties:
+
+```js
+{
+ options: {...} // Original parameters passed
+ src: "https//..." // Path to the generated image
+ attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..)
+}
+```
## Alt Text
Not all users can see images in the same way, so accessibility is an especially important concern when using images. Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images.
-This attribute is required for the image integration's `` and `` components. These components will throw an error if no alt text is provided.
+This attribute is required for the `` component. `` will throw an error if no alt text is provided.
If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set `alt=""` so that screen readers know to ignore the image.
+## Default image service
+
+[Sharp](https://github.com/lovell/sharp) is the default image service used for `astro:assets`.
+
+If you would prefer to use [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images, update your config with the following:
+```js title="astro.config.mjs" ins={4-6}
+import { defineConfig, squooshImageService } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+});
+```
## Community Integrations
-In addition to the official [`@astrojs/image`](/en/guides/integrations-guide/image/) integration, there are several third-party [community image integrations](https://astro.build/integrations?search=images) for optimizing and working with images in your Astro project.
+There are several third-party [community image integrations](https://astro.build/integrations?search=images) for optimizing and working with images in your Astro project.
+
+## Upgrade to v3.0 from v2.x
+
+`astro:assets` is no longer behind an experimental flag in Astro v3.0.
+
+`` is now a built-in component and the previous `@astrojs/image` integration has been removed.
+
+These and other accompanying changes to using images in Astro may cause some breaking changes when you upgrade your Astro project from an earlier version.
+
+Please follow the instructions below as appropriate to upgrade an Astro v2.x project to v3.0.
+
+### Upgrade from `experimental.assets`
+
+If you had previously enabled the experimental flag for `astro:assets`, you will need to update your project for Astro v3.0 which now includes assets features by default.
+
+#### Remove `experimental.assets` flag
+
+Remove the experimental flag:
+
+```js title="astro.config.mjs" del={4-6}
+import { defineConfig } from 'astro/config';
+
+export default defineConfig({
+ experimental: {
+ assets: true
+ }
+});
+```
+
+If necessary, also update your `src/env.d.ts` file to replace the `astro/client-image` reference with `astro/client`:
+
+```ts title="src/env.d.ts" del={1} ins={2}
+///
+///
+```
+
+#### Remove the `~/assets` import alias
+
+This import alias is no longer included by default with `astro:assets`. If you were using this alias with experimental assets, you must convert them to relative file paths, or [create your own import aliases](/en/guides/aliases/).
+
+```astro title="src/pages/posts/post-1.astro" del={2} ins={3}
+---
+import rocket from '~/assets/rocket.png'
+import rocket from '../../assets/rocket.png';
+---
+```
+
+#### Add simple asset support for Cloudflare, Deno, Vercel Edge and Netlify Edge
+
+ Astro v3.0 allows `astro:assets` to work without errors in Cloudflare, Deno, Vercel Edge and Netlify Edge, which do not support Astro's built-in Squoosh and Sharp image optimization. Note that Astro does not perform any image transformation and processing in these environments. However, you can still enjoy the other benefits of using `astro:assets`, including no Cumulative Layout Shift (CLS), the enforced `alt` attribute, and a consistent authoring experience.
+
+ If you previously avoided using `astro:assets` because of these constraints, you can now use them without issues. You can configure the no-op image service to explicitly opt-in to this behavior:
+
+```js title="astro.config.mjs" ins={4-8}
+import { defineConfig } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: {
+ entrypoint: 'astro/assets/services/noop'
+ }
+ }
+});
+```
+
+### Decide where to store your images
+
+See the Images guide to help you decide [where to store your images](#where-to-store-images). You may wish to take advantage of new options for storing your images with the added flexibility `astro:assets` brings. For example, relative images from your project `src/` can now be referenced in Markdown, MDX, and Markdoc using standard Markdown `` syntax.
+
+### Update existing `` tags
+
+Previously, importing an image would return a simple `string` with the path of the image. Now, imported image assets match the following signature:
+
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
+
+You must update the `src` attribute of any existing `` tags (including any [images in UI framework components](#images-in-ui-framework-components)) and you may also update other attributes that are now available to you from the imported image.
+
+```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={4} ins={6}
+---
+import rocket from '../images/rocket.svg';
+---
+
+
+
+```
+
+### Update your Markdown, MDX, and Markdoc files
+
+Relative images from your project `src/` can now be referenced in Markdown, MDX, and Markdoc using standard Markdown `` syntax.
+
+This allows you to move your images from the `public/` directory to your project `src/` where they will now be processed and optimized. Your existing images in `public/` and remote images are still valid but are not optimized by Astro's build process.
+
+```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/"
+# My Markdown Page
+
+
+
+
+
+
+```
+
+If you require more control over your image attributes, we recommend using the `.mdx` file format, which allows you to include Astro's `` component or a JSX `` tag in addition to the Markdown syntax. Use the [MDX integration](/en/guides/integrations-guide/mdx/) to add support for MDX to Astro.
+
+### Remove `@astrojs/image`
+
+
+If you were using the image integration in Astro v2.x, complete the following steps:
+
+1. Remove the `@astrojs/image` integration.
+
+ You must [remove the integration](/en/guides/integrations-guide/#removing-an-integration) by uninstalling and then removing it from your `astro.config.mjs` file.
+
+ ```js del={3,7}
+ // astro.config.mjs
+ import { defineConfig } from 'astro/config';
+ import image from '@astrojs/image';
+
+ export default defineConfig({
+ integrations: [
+ image(),
+ ]
+ })
+ ```
+
+2. Migrate any existing `` components.
+
+ Change all `import` statements from `@astrojs/image/components` to `astro:assets` in order to use the new built-in `` component.
+
+ Remove any component attributes that are not [currently supported image asset properties](/en/guides/images/#properties).
+
+ For example, `aspectRatio` is no longer supported, as it is now automatically inferred from the `width` and `height` attributes.
+
+ ```astro title="src/components/MyComponent.astro" del= {2,11} ins={3}
+ ---
+ import { Image } from '@astrojs/image/components';
+ import { Image } from 'astro:assets'
+ import localImage from "../assets/logo.png";
+ const localAlt = "The Astro Logo";
+ ---
+
+
+ ```
+
+3. Remove any existing `` components.
+
+ Currently, the built-in assets feature does not include a `` component.
+
+ Instead, you can use the HTML image attributes `srcset` and `sizes` or the `` tag [for art direction or to create responsive images](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction).
+
+4. Choose a default image service.
+
+ [Sharp](https://github.com/lovell/sharp) is now the default image service used for `astro:assets`. If you would like to use Sharp, no configuration is required.
+
+ If you would prefer to use [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images, update your config with the following `image.service` option:
+
+ ```js title="astro.config.mjs" ins={4-6}
+ import { defineConfig, squooshImageService } from 'astro/config';
+
+ export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+ });
+ ```
+
+### Update Content Collections schemas
+
+You can now declare an associated image for a content collections entry, such as a blog post's cover image, in your frontmatter using its path relative to the current folder.
+
+The new `image` helper for content collections lets you validate the image metadata using Zod. Learn more about [how to use images in content collections](/en/guides/images/#images-in-content-collections)
diff --git a/src/content/docs/en/guides/integrations-guide.mdx b/src/content/docs/en/guides/integrations-guide.mdx
index 2a512ca2dd279..b95b5f0fd4160 100644
--- a/src/content/docs/en/guides/integrations-guide.mdx
+++ b/src/content/docs/en/guides/integrations-guide.mdx
@@ -126,17 +126,17 @@ To remove an integration, first uninstall the integration from your project
```shell
- npm uninstall @astrojs/image
+ npm uninstall @astrojs/react
```
```shell
- pnpm uninstall @astrojs/image
+ pnpm uninstall @astrojs/react
```
```shell
- yarn remove @astrojs/image
+ yarn remove @astrojs/react
```
@@ -146,11 +146,11 @@ Next, remove the integration from your `astro.config.*` file:
```js title="astro.config.mjs" del={3,7}
import { defineConfig } from 'astro/config'
-import image from "@astrojs/image";
+import react from "@astrojs/react";
export default defineConfig({
integrations: [
- image()
+ react()
]
})
```
diff --git a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx
index a000c5203b6cb..9f2dc2e005b4f 100644
--- a/src/content/docs/en/guides/integrations-guide/cloudflare.mdx
+++ b/src/content/docs/en/guides/integrations-guide/cloudflare.mdx
@@ -65,23 +65,37 @@ export default defineConfig({
default `"advanced"`
-Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root.
+Cloudflare Pages has 2 different modes for deploying functions, `advanced` mode which picks up the `_worker.js` in `dist`, or a directory mode where pages will compile the worker out of a functions folder in the project root. For most projects the adapter default of `advanced` will be sufficient; the `dist` folder will contain your compiled project.
-For most projects the adapter default of `advanced` will be sufficient; the `dist` folder will contain your compiled project. Switching to directory mode allows you to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) or write custom code to enable logging.
+#### `mode:directory`
-In directory mode, the adapter will compile the client side part of your app the same way by default, but moves the worker script into a `functions` folder in the project root. In this case, the adapter will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middleware which can be checked into version control.
-
-With the build configuration `split: true`, the adapter instead compiles a separate bundle for each page. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing `functions` files with identical names, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
-
-Note that this adapter does not support using [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro will bundle the [Astro middleware](/en/guides/middleware/) into each page.
+Switching to directory mode allows you to use [pages plugins](https://developers.cloudflare.com/pages/platform/functions/plugins/) such as [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) or write custom code to enable logging.
```ts
-// directory mode
+// astro.config.mjs
export default defineConfig({
adapter: cloudflare({ mode: 'directory' }),
});
```
+In `directory` mode, the adapter will compile the client-side part of your app the same way as in `advanced` mode by default, but moves the worker script into a `functions` folder in the project root. In this case, the adapter will only ever place a `[[path]].js` in that folder, allowing you to add additional plugins and pages middleware which can be checked into version control.
+
+To instead compile a separate bundle for each page, set the `functionPerPath` option in your Cloudflare adapter config. This option requires some manual maintenance of the `functions` folder. Files emitted by Astro will overwrite existing `functions` files with identical names, so you must choose unique file names for each file you manually add. Additionally, the adapter will never empty the `functions` folder of outdated files, so you must clean up the folder manually when you remove pages.
+
+```diff
+import {defineConfig} from "astro/config";
+import cloudflare from '@astrojs/cloudflare';
+
+export default defineConfig({
+ adapter: cloudflare({
+ mode: 'directory',
++ functionPerRoute: true
+ })
+})
+```
+
+Note that this adapter does not support using [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro will bundle the [Astro middleware](/en/guides/middleware/) into each page.
+
## Enabling Preview
In order for preview to work you must install `wrangler`
@@ -156,7 +170,7 @@ See Cloudflare's documentation for [working with environment variables](https://
```js
// pages/[id].json.js
-export function get({ params }) {
+export function GET({ params }) {
// Access environment variables per request inside a function
const serverUrl = import.meta.env.SERVER_URL;
const result = await fetch(serverUrl + "/user/" + params.id);
diff --git a/src/content/docs/en/guides/integrations-guide/image.mdx b/src/content/docs/en/guides/integrations-guide/image.mdx
deleted file mode 100644
index eacbc72045017..0000000000000
--- a/src/content/docs/en/guides/integrations-guide/image.mdx
+++ /dev/null
@@ -1,750 +0,0 @@
----
-# NOTE: This file is auto-generated from 'scripts/generate-integration-pages.ts'
-# and pulls content directly from the package’s README.
-# DO NOT MAKE EDITS TO THIS FILE DIRECTLY, THEY WILL BE OVERWRITTEN!
-# For corrections, please edit the package README at
-# https://github.com/withastro/astro/tree/main/packages/integrations/image/
-#
-# TRANSLATORS: please remove this note and the component.
-
-type: integration
-title: '@astrojs/image'
-description: Learn how to use the @astrojs/image integration in your Astro project.
-githubURL: 'https://github.com/withastro/astro/tree/main/packages/integrations/image/'
-hasREADME: true
-category: other
-i18nReady: true
----
-
-import Video from '~/components/Video.astro';
-import DontEditWarning from '~/components/DontEditWarning.astro';
-
-
-
-> ⚠️ This integration will be deprecated in Astro v3.0 (Fall 2023) in favor of the `astro:assets` module. Please see the [Assets documentation](/en/guides/assets/) for more information.
-
-This **[Astro integration][astro-integration]** optimizes images in your [Astro project](https://astro.build/). It is supported in Astro v2 only for all static sites and for [some server-side rendering deploy hosts](#installation).
-
-## Why `@astrojs/image`?
-
-Images play a big role in overall site performance and usability. Serving properly sized images makes all the difference but is often tricky to automate.
-
-This integration provides `` and `` components as well as a basic image transformer, with full support for static sites and server-side rendering. The built-in image transformer is also replaceable, opening the door for future integrations that work with your favorite hosted image service.
-
-## Installation
-
-Along with our integration, we recommend installing [sharp](https://sharp.pixelplumbing.com/) when appropriate.
-
-The `@astrojs/image` default image transformer is based on [Squoosh](https://github.com/GoogleChromeLabs/squoosh) and uses WebAssembly libraries to support most deployment environments, including those that do not support sharp, such as StackBlitz.
-
-For faster builds and more fine-grained control of image transformations, install sharp in addition to `@astrojs/image` if
-
-* You are building a static site with Astro.
-* You are using an SSR deployment host that supports NodeJS using `@astrojs/netlify/functions`, `@astrojs/vercel/serverless` or `@astrojs/node`.
-
-Note that `@astrojs/image` is not currently supported on
-
-* Cloudflare SSR
-* `@astrojs/deno`
-* `@astrojs/netlify/edge-functions`
-* `@astrojs/vercel/edge`
-
-### Quick Install
-
-The `astro add` command-line tool automates the installation for you. Run one of the following commands in a new terminal window. (If you aren't sure which package manager you're using, run the first command.) Then, follow the prompts, and type "y" in the terminal (meaning "yes") for each one.
-
-```sh
-# Using NPM
-npx astro add image
-# Using Yarn
-yarn astro add image
-# Using PNPM
-pnpm astro add image
-```
-
-If you run into any issues, [feel free to report them to us on GitHub](https://github.com/withastro/astro/issues) and try the manual installation steps below.
-
-### Manual Install
-
-First, install the `@astrojs/image` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
-
-```sh
-npm install @astrojs/image
-```
-
-Then, apply this integration to your `astro.config.*` file using the `integrations` property:
-
-```js ins={3} "image()"
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- // ...
- integrations: [image()],
-});
-```
-
-### Installing `sharp` (optional)
-
-First, install the `sharp` package using your package manager. If you're using npm or aren't sure, run this in the terminal:
-
-```sh
-npm install sharp
-```
-
-Then, update the integration in your `astro.config.*` file to use the built-in `sharp` image transformer.
-
-```js ins={8}
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- // ...
- integrations: [
- image({
- serviceEntryPoint: '@astrojs/image/sharp',
- }),
- ],
-});
-```
-
-### Update `env.d.ts`
-
-For the best development experience, add the integrations type definitions to your project's `env.d.ts` file.
-
-```typescript
-// Replace `astro/client` with `@astrojs/image/client`
-///
-```
-
-Or, alternatively if your project is using the types through a `tsconfig.json`
-
-```json
-{
- "compilerOptions": {
- // Replace `astro/client` with `@astrojs/image/client`
- "types": ["@astrojs/image/client"]
- }
-}
-```
-
-## Usage
-
-```astro title="src/pages/index.astro"
----
-import { Image, Picture } from '@astrojs/image/components';
-import heroImage from '../assets/hero.png';
----
-
-// optimized image, keeping the original width, height, and image format
-
-
-// specify multiple sizes for responsive images or art direction
-
----
-```
-
-The included image transformers support resizing images and encoding them to different image formats. Third-party image services will be able to add support for custom transformations as well (ex: `blur`, `filter`, `rotate`, etc).
-
-Astro’s `` and `` components require the `alt` attribute, which provides descriptive text for images. A warning will be logged if alt text is missing, and a future release of the integration will throw an error if no alt text is provided.
-
-If the image is merely decorative (i.e. doesn’t contribute to the understanding of the page), set `alt=""` so that the image is properly understood and ignored by screen readers.
-
-### ``
-
-The built-in `` component is used to create an optimized `` for both remote images accessed by URL as well as local images imported from your project's `src/` directory.
-
-In addition to the component-specific properties, any valid HTML attribute for the `` included in the `` component will be included in the built ``.
-
-#### src
-
-
-
-Source for the original image file.
-
-For remote images, provide the full URL. (e.g. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`)
-
-For images located in your project's `src/`: use the file path relative to the `src/` directory. (e.g. `src="../assets/source-pic.png"`)
-
-For images located in your `public/` directory: use the URL path relative to the `public/` directory. (e.g. `src="/images/public-image.jpg"`). These work like remote images.
-
-#### alt
-
-
-
-**Type:** `string`
-**Required:** `true`
-
-
-
-Defines an alternative text description of the image.
-
-Set to an empty string (`alt=""`) if the image is not a key part of the content (e.g. it's decoration or a tracking pixel).
-
-#### format
-
-
-
-The output format to be used in the optimized image. The original image format will be used if `format` is not provided.
-
-This property is required for remote images when using the default image transformer Squoosh, this is because the original format cannot be inferred.
-
-Added in v0.15.0: You can use the `` component when working with SVG images, but the `svg` option can only be used when the original image is a `.svg` file. Other image formats (like `.png` or `.jpg`) cannot be converted into vector images. The `.svg` image itself will not be transformed, but the final `` will be properly optimized by the integration.
-
-#### quality
-
-
-
-The compression quality used during optimization. The image service will use its own default quality depending on the image format if not provided.
-
-#### width
-
-
-
-The desired width of the output image. Combine with `height` to crop the image to an exact size, or `aspectRatio` to automatically calculate and crop the height.
-
-Dimensions are optional for local images, the original image size will be used if not provided.
-
-For remote images, including images in `public/`, the integration needs to be able to calculate dimensions for the optimized image. This can be done by providing `width` and `height` or by providing one dimension and an `aspectRatio`.
-
-#### height
-
-
-
-The desired height of the output image. Combine with `width` to crop the image to an exact size, or `aspectRatio` to automatically calculate and crop the width.
-
-Dimensions are optional for local images, the original image size will be used if not provided.
-
-For remote images, including images in `public/`, the integration needs to be able to calculate dimensions for the optimized image. This can be done by providing `width` and `height` or by providing one dimension and an `aspectRatio`.
-
-#### aspectRatio
-
-
-
-The desired aspect ratio of the output image. Combine with either `width` or `height` to automatically calculate and crop the other dimension.
-
-A `string` can be provided in the form of `{width}:{height}`, ex: `16:9` or `3:4`.
-
-A `number` can also be provided, useful when the aspect ratio is calculated at build time. This can be an inline number such as `1.777` or inlined as a JSX expression like `aspectRatio={16/9}`.
-
-For remote images, including images in `public/`, the integration needs to be able to calculate dimensions for the optimized image. This can be done by providing `width` and `height` or by providing one dimension and an `aspectRatio`.
-
-#### background
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
-
-The background color is used to fill the remaining background when using `contain` for the `fit` property.
-
-The background color is also used for replacing the alpha channel with `sharp`'s `flatten` method. In case the output format
-doesn't support transparency (i.e. `jpeg`), it's advisable to include a background color, otherwise black will be used
-as default replacement for transparent pixels.
-
-The parameter accepts a `string` as value.
-
-The parameter can be a [named HTML color](https://www.w3schools.com/tags/ref_colornames.asp), a hexadecimal
-color representation with 3 or 6 hexadecimal characters in the form `#123[abc]`, an RGB definition in the form
-`rgb(100,100,100)`, an RGBA definition in the form `rgba(100,100,100, 0.5)`.
-
-#### fit
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead. Read more about [how `sharp` resizes images](https://sharp.pixelplumbing.com/api-resize).
-
-How the image should be resized to fit both `height` and `width`.
-
-#### position
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead. Read more about [how `sharp` resizes images](https://sharp.pixelplumbing.com/api-resize).
-
-Position of the crop when fit is `cover` or `contain`.
-
-### ``
-
-The built-in `` component is used to create an optimized `` for both remote images accessed by URL as well as local images imported from your project's `src/` directory.
-
-In addition to the component-specific properties, any valid HTML attribute for the `` included in the `` component will be included in the built ``.
-
-#### src
-
-
-
-Source for the original image file.
-
-For remote images, provide the full URL. (e.g. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`)
-
-For images located in your project's `src/`: use the file path relative to the `src/` directory. (e.g. `src="../assets/source-pic.png"`)
-
-For images located in your `public/` directory: use the URL path relative to the `public/` directory. (e.g. `src="/images/public-image.jpg"`). These work like remote images.
-
-#### alt
-
-
-
-**Type:** `string`
-**Required:** `true`
-
-
-
-Defines an alternative text description of the image.
-
-Set to an empty string (`alt=""`) if the image is not a key part of the content (e.g. it's decoration or a tracking pixel).
-
-#### sizes
-
-
-
-**Type:** `string`
-**Required:** `true`
-
-
-
-The HTMLImageElement property `sizes` allows you to specify the layout width of the image for each of a list of media conditions.
-
-See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) for more details.
-
-#### widths
-
-
-
-**Type:** `number[]`
-**Required:** `true`
-
-
-
-The list of sizes that should be built for responsive images. This is combined with `aspectRatio` to calculate the final dimensions of each built image.
-
-```astro
-// Builds three images: 400x400, 800x800, and 1200x1200
-
-```
-
-#### aspectRatio
-
-
-
-The desired aspect ratio of the output image. This is combined with `widths` to calculate the final dimensions of each built image.
-
-A `string` can be provided in the form of `{width}:{height}`, ex: `16:9` or `3:4`.
-
-A `number` can also be provided, useful when the aspect ratio is calculated at build time. This can be an inline number such as `1.777` or inlined as a JSX expression like `aspectRatio={16/9}`.
-
-For remote images, including images in `public/`, `aspectRatio` is required to ensure the correct `height` can be calculated at build time.
-
-#### formats
-
-
-
-The output formats to be used in the optimized image. If not provided, `webp` and `avif` will be used in addition to the original image format.
-
-For remote images, including images in `public/`, the original image format is unknown. If not provided, only `webp` and `avif` will be used.
-
-#### background
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead.
-
-The background color to use for replacing the alpha channel with `sharp`'s `flatten` method. In case the output format
-doesn't support transparency (i.e. `jpeg`), it's advisable to include a background color, otherwise black will be used
-as default replacement for transparent pixels.
-
-The parameter accepts a `string` as value.
-
-The parameter can be a [named HTML color](https://www.w3schools.com/tags/ref_colornames.asp), a hexadecimal
-color representation with 3 or 6 hexadecimal characters in the form `#123[abc]`, or an RGB definition in the form
-`rgb(100,100,100)`.
-
-#### fit
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead. Read more about [how `sharp` resizes images](https://sharp.pixelplumbing.com/api-resize).
-
-How the image should be resized to fit both `height` and `width`.
-
-#### position
-
-
-
-> This is not supported by the default Squoosh service. See the [installation section](#installing-sharp-optional) for details on using the `sharp` service instead. Read more about [how `sharp` resizes images](https://sharp.pixelplumbing.com/api-resize).
-
-Position of the crop when fit is `cover` or `contain`.
-
-### `getImage`
-
-This is the helper function used by the `` component to build `` attributes for the transformed image. This helper can be used directly for more complex use cases that aren't currently supported by the `` component.
-
-This helper takes in an object with the same properties as the `` component and returns an object with attributes that should be included on the final `` element.
-
-This can be helpful if you need to add preload links to a page's ``.
-
-```astro
----
-import { getImage } from '@astrojs/image';
-
-const { src } = await getImage({
- src: import('../assets/hero.png'),
- alt: 'My hero image',
-});
----
-
-
-
-
-
-
-```
-
-### `getPicture`
-
-This is the helper function used by the `` component to build multiple sizes and formats for responsive images. This helper can be used directly for more complex use cases that aren't currently supported by the `` component.
-
-This helper takes in an object with the same properties as the `` component and returns an object attributes that should be included on the final `` element **and** a list of sources that should be used to render all ``s for the `` element.
-
-## Configuration
-
-The integration can be configured to run with a different image service, either a hosted image service or a full image transformer that runs locally in your build or SSR deployment.
-
-> During development, local images may not have been published yet and would not be available to hosted image services. Local images will always use the built-in image service when using `astro dev`.
-
-### config.serviceEntryPoint
-
-The `serviceEntryPoint` should resolve to the image service installed from NPM. The default entry point is `@astrojs/image/squoosh`, which resolves to the entry point exported from this integration's `package.json`.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [
- image({
- // Example: The entrypoint for a third-party image service installed from NPM
- serviceEntryPoint: 'my-image-service/astro.js',
- }),
- ],
-});
-```
-
-### config.logLevel
-
-The `logLevel` controls can be used to control how much detail is logged by the integration during builds. This may be useful to track down a specific image or transformation that is taking a long time to build.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [
- image({
- // supported levels: 'debug' | 'info' | 'warn' | 'error' | 'silent'
- // default: 'info'
- logLevel: 'debug',
- }),
- ],
-});
-```
-
-### config.cacheDir
-
-During static builds, the integration will cache transformed images to avoid rebuilding the same image for every build. This can be particularly helpful if you are using a hosting service that allows you to cache build assets for future deployments.
-
-Local images will be cached for 1 year and invalidated when the original image file is changed. Remote images will be cached based on the `fetch()` response's cache headers, similar to how a CDN would manage the cache.
-
-By default, transformed images will be cached to `./node_modules/.astro/image`. This can be configured in the integration's config options.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [
- image({
- // may be useful if your hosting provider allows caching between CI builds
- cacheDir: './.cache/image',
- }),
- ],
-});
-```
-
-Caching can also be disabled by using `cacheDir: false`.
-
-## Examples
-
-### Local images
-
-Image files in your project's `src/` directory can be imported in frontmatter and passed directly to the `` component as the `src=` attribute value. `alt` is also required.
-
-All other properties are optional and will default to the original image file's properties if not provided.
-
-```astro
----
-import { Image } from '@astrojs/image/components';
-import heroImage from '../assets/hero.png';
----
-
-// optimized image, keeping the original width, height, and image format
-
-
-// height will be recalculated to match the original aspect ratio
-
-
-// cropping to a specific width and height
-
-
-// cropping to a specific aspect ratio and converting to an avif format
-
-
-// image imports can also be inlined directly
-
-```
-
-#### Images in `/public`
-
-The `` component can also be used with images stored in the `public/` directory and the `src=` attribute is relative to the public folder. It will be treated as a remote image, which requires either both `width` and `height`, or one dimension and an `aspectRatio` attribute.
-
-Your original image will be copied unprocessed to the build folder, like all files located in public/, and Astro’s image integration will also return optimized versions of the image.
-
-For example, use an image located at `public/social.png` in either static or SSR builds like so:
-
-```astro title="src/pages/page.astro"
----
-import { Image } from '@astrojs/image/components';
-import socialImage from '/social.png';
----
-
-// In static builds: the image will be built and optimized to `/dist`. // In SSR builds: the image
-will be optimized by the server when requested by a browser.
-
-```
-
-### Remote images
-
-Remote images can be transformed with the `` component. The `` component needs to know the final dimensions for the `` element to avoid content layout shifts. For remote images, this means you must either provide `width` and `height`, or one of the dimensions plus the required `aspectRatio`.
-
-```astro
----
-import { Image } from '@astrojs/image/components';
-
-const imageUrl = 'https://astro.build/assets/press/full-logo-dark.png';
----
-
-// cropping to a specific width and height
-
-
-// height will be recalculated to match the aspect ratio
-
-```
-
-### Responsive pictures
-
-The `` component can be used to automatically build a `` with multiple sizes and formats. Check out [MDN](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction) for a deep dive into responsive images and art direction.
-
-By default, the picture will include formats for `avif` and `webp`. For local images only, the image's original format will also be included.
-
-For remote images, an `aspectRatio` is required to ensure the correct `height` can be calculated at build time.
-
-```astro
----
-import { Picture } from '@astrojs/image/components';
-import hero from '../assets/hero.png';
-
-const imageUrl =
- 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
----
-
-// Local image with multiple sizes
-
-
-// Remote image (aspect ratio is required)
-
-
-// Inlined imports are supported
-
-```
-
-### Setting Default Values
-
-Currently, there is no way to specify default values for all `` and `` components. Required attributes should be set on each individual component.
-
-As an alternative, you can wrap these components in another Astro component for reuse. For example, you could create a component for your blog post images:
-
-```astro title="src/components/BlogPostImage.astro"
----
-import { Picture } from '@astrojs/image/components';
-
-const { src, ...attrs } = Astro.props;
----
-
-
-
-
-```
-
-### Using `` with the Image Integration
-
-The official image integration will change image imports to return an object rather than a source string.
-The object has the following properties, derived from the imported file:
-
-```ts
-{
- src: string;
- width: number;
- height: number;
- format: 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp';
-}
-```
-
-If you have the image integration installed, refer to the `src` property of the object when using ``.
-
-```astro ".src"
----
-import rocket from '../images/rocket.svg';
----
-
-
-```
-
-Alternatively, add `?url` to your imports to tell them to return a source string.
-
-```astro "?url"
----
-import rocket from '../images/rocket.svg?url';
----
-
-
-```
-
-## Troubleshooting
-
-* If your installation doesn't seem to be working, try restarting the dev server.
-* If you edit and save a file and don't see your site update accordingly, try refreshing the page.
-* If refreshing the page doesn't update your preview, or if a new installation doesn't seem to be working, then restart the dev server.
-
-For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
-
-You can also check our [Astro Integration Documentation][astro-integration] for more on integrations.
-
-[astro-integration]: /en/guides/integrations-guide/
-
-## Contributing
-
-This package is maintained by Astro's Core team. You're welcome to submit an issue or PR!
-
-## Changelog
-
-See [CHANGELOG.md](https://github.com/withastro/astro/tree/main/packages/integrations/image/CHANGELOG.md) for a history of changes to this integration.
diff --git a/src/content/docs/en/guides/integrations-guide/markdoc.mdx b/src/content/docs/en/guides/integrations-guide/markdoc.mdx
index 8eab45a82a823..0358456dfeb63 100644
--- a/src/content/docs/en/guides/integrations-guide/markdoc.mdx
+++ b/src/content/docs/en/guides/integrations-guide/markdoc.mdx
@@ -356,6 +356,36 @@ Now, you can call this function from any Markdoc content entry:
📚 [See the Markdoc documentation](https://markdoc.dev/docs/functions#creating-a-custom-function) for more on using variables or functions in your content.
+### Markdoc Language Server
+
+If you are using VS Code, there is an official [Markdoc language extension](https://marketplace.visualstudio.com/items?itemName=Stripe.markdoc-language-support) that includes syntax highlighting and autocomplete for configured tags. [See the language server on GitHub](https://github.com/markdoc/language-server.git) for more information.
+
+To set up the extension, create a `markdoc.config.json` file into the project root with following content:
+
+```json
+[
+ {
+ "id": "my-site",
+ "path": "src/content",
+ "schema": {
+ "path": "markdoc.config.mjs",
+ "type": "esm",
+ "property": "default",
+ "watch": true
+ }
+ }
+]
+```
+
+The `schema` property contains all information to configure the language server for Astro content collections. It accepts following properties:
+
+* `path`: The path to the configuration file.
+* `type`: The type of module your configuration file uses (`esm` allows `import` syntax).
+* `property`: The exported property name that contains the configuration object.
+* `watch`: Tell the server to watch for changes in the configuration.
+
+The top-level `path` property tells the server where content is located. Since Markdoc is specific to content collections, you can use `src/content`.
+
### Pass Markdoc variables
You may need to pass [variables][markdoc-variables] to your content. This is useful when passing SSR parameters like A/B tests.
diff --git a/src/content/docs/en/guides/integrations-guide/mdx.mdx b/src/content/docs/en/guides/integrations-guide/mdx.mdx
index 26d448b44e146..7e0c7a418df19 100644
--- a/src/content/docs/en/guides/integrations-guide/mdx.mdx
+++ b/src/content/docs/en/guides/integrations-guide/mdx.mdx
@@ -81,7 +81,7 @@ export default defineConfig({
With the Astro MDX integration, you can [add MDX pages to your project](/en/guides/markdown-content/#markdown-and-mdx-pages) by adding `.mdx` files within your `src/pages/` directory. You can also [import `.mdx` files](/en/guides/markdown-content/#importing-markdown) into `.astro` files.
-Astro's MDX integration adds extra features to standard MDX, including Markdown-style frontmatter. This allows you to use most of Astro's built-in Markdown features like a [special frontmatter `layout` property](/en/guides/markdown-content/#frontmatter-layout) and a [property for marking a page as a draft](/en/guides/markdown-content/#draft-pages).
+Astro's MDX integration adds extra features to standard MDX, including Markdown-style frontmatter. This allows you to use most of Astro's built-in Markdown features like a [special frontmatter `layout` property](/en/guides/markdown-content/#frontmatter-layout).
See how MDX works in Astro with examples in our [Markdown & MDX guide](/en/guides/markdown-content/).
diff --git a/src/content/docs/en/guides/integrations-guide/netlify.mdx b/src/content/docs/en/guides/integrations-guide/netlify.mdx
index cac5f43d478d8..128bb3e32038d 100644
--- a/src/content/docs/en/guides/integrations-guide/netlify.mdx
+++ b/src/content/docs/en/guides/integrations-guide/netlify.mdx
@@ -69,28 +69,11 @@ If you prefer to install the adapter manually instead, complete the following tw
});
```
-### Edge Functions
-
-Netlify has two serverless platforms, [Netlify Functions](https://docs.netlify.com/functions/overview/) and [Netlify Edge Functions](https://docs.netlify.com/edge-functions/overview/). With Edge Functions your code is distributed closer to your users, lowering latency.
-
-To deploy with Edge Functions, use `netlify/edge-functions` in the Astro config file instead of `netlify/functions`.
-
-```js ins={3}
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import netlify from '@astrojs/netlify/edge-functions';
-
-export default defineConfig({
- output: 'server',
- adapter: netlify(),
-});
-```
-
### Run middleware in Edge Functions
When deploying to Netlify Functions, you can choose to use an Edge Function to run your Astro middleware.
-To enable this, set the `build.excludeMiddleware` Astro config option to `true`:
+To enable this, set the `edgeMiddleware` config option to `true`:
```js ins={9}
// astro.config.mjs
@@ -99,10 +82,9 @@ import netlify from '@astrojs/netlify/functions';
export default defineConfig({
output: 'server',
- adapter: netlify(),
- build: {
- excludeMiddleware: true,
- },
+ adapter: netlify({
+ edgeMiddleware: true,
+ }),
});
```
@@ -148,10 +130,9 @@ import netlify from '@astrojs/netlify/functions';
export default defineConfig({
output: 'server',
- adapter: netlify(),
- build: {
- split: true,
- },
+ adapter: netlify({
+ functionPerRoute: true,
+ }),
});
```
@@ -276,7 +257,7 @@ We check for common mime types for audio, image, and video files. To include spe
import fs from 'node:fs';
-export function get() {
+export function GET() {
const buffer = fs.readFileSync('../image.jpg');
// Return the buffer directly, @astrojs/netlify will base64 encode the body
diff --git a/src/content/docs/en/guides/integrations-guide/node.mdx b/src/content/docs/en/guides/integrations-guide/node.mdx
index 6390c8d9fbeee..4708c89af5163 100644
--- a/src/content/docs/en/guides/integrations-guide/node.mdx
+++ b/src/content/docs/en/guides/integrations-guide/node.mdx
@@ -174,7 +174,7 @@ For standalone mode the server handles file servering in addition to the page an
You can override the host and port the standalone server runs on by passing them as environment variables at runtime:
```shell
-HOST=0.0.0.0 PORT=3000 node ./dist/server/entry.mjs
+HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs
```
#### HTTPS
diff --git a/src/content/docs/en/guides/integrations-guide/preact.mdx b/src/content/docs/en/guides/integrations-guide/preact.mdx
index 4aa862623bcf9..3d02d9e0f22cf 100644
--- a/src/content/docs/en/guides/integrations-guide/preact.mdx
+++ b/src/content/docs/en/guides/integrations-guide/preact.mdx
@@ -128,6 +128,41 @@ Check out the [`pnpm` overrides](https://pnpm.io/package_json#pnpmoverrides) and
Currently, the `compat` option only works for React libraries that export code as ESM. If an error happens during build-time, try adding the library to `vite.ssr.noExternal: ['the-react-library']` in your `astro.config.mjs` file.
:::
+## Options
+
+### Combining multiple JSX frameworks
+
+When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed.
+
+Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths.
+
+We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Enable many frameworks to support all different kinds of components.
+ // No `include` is needed if you are only using a single JSX framework!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
## Examples
* The [Astro Preact example](https://github.com/withastro/astro/tree/latest/examples/framework-preact) shows how to use an interactive Preact component in an Astro project.
diff --git a/src/content/docs/en/guides/integrations-guide/react.mdx b/src/content/docs/en/guides/integrations-guide/react.mdx
index 0fdf9257fbcfe..633f6b417dde0 100644
--- a/src/content/docs/en/guides/integrations-guide/react.mdx
+++ b/src/content/docs/en/guides/integrations-guide/react.mdx
@@ -84,6 +84,39 @@ To use your first React component in Astro, head to our [UI framework documentat
## Options
+### Combining multiple JSX frameworks
+
+When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed.
+
+Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths.
+
+We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Enable many frameworks to support all different kinds of components.
+ // No `include` is needed if you are only using a single JSX framework!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
### Children parsing
Children passed into a React component from an Astro component are parsed as plain strings, not React nodes.
@@ -101,7 +134,7 @@ import ReactComponent from './ReactComponent';
```
-If you are using a library that *expects* more than one child element element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker.
+If you are using a library that *expects* more than one child element to be passed, for example so that it can slot certain elements in different places, you might find this to be a blocker.
You can set the experimental flag `experimentalReactChildren` to tell Astro to always pass children to React as React vnodes. There is some runtime cost to this, but it can help with compatibility.
diff --git a/src/content/docs/en/guides/integrations-guide/solid-js.mdx b/src/content/docs/en/guides/integrations-guide/solid-js.mdx
index 68c766632aea8..b4d9baf047a2a 100644
--- a/src/content/docs/en/guides/integrations-guide/solid-js.mdx
+++ b/src/content/docs/en/guides/integrations-guide/solid-js.mdx
@@ -82,6 +82,41 @@ To use your first SolidJS component in Astro, head to our [UI framework document
* 💧 client-side hydration options, and
* 🤝 opportunities to mix and nest frameworks together
+## Options
+
+### Combining multiple JSX frameworks
+
+When you are using multiple JSX frameworks (React, Preact, Solid) in the same project, Astro needs to determine which JSX framework-specific transformations should be used for each of your components. If you have only added one JSX framework integration to your project, no extra configuration is needed.
+
+Use the `include` (required) and `exclude` (optional) configuration options to specify which files belong to which framework. Provide an array of files and/or folders to `include` for each framework you are using. Wildcards may be used to include multiple file paths.
+
+We recommend placing common framework components in the same folder (e.g. `/components/react/` and `/components/solid/`) to make specifying your includes easier, but this is not required:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Enable many frameworks to support all different kinds of components.
+ // No `include` is needed if you are only using a single JSX framework!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
## Troubleshooting
For help, check out the `#support` channel on [Discord](https://astro.build/chat). Our friendly Support Squad members are here to help!
diff --git a/src/content/docs/en/guides/integrations-guide/vercel.mdx b/src/content/docs/en/guides/integrations-guide/vercel.mdx
index 2e3c88f528f71..2bf9dc3d1e185 100644
--- a/src/content/docs/en/guides/integrations-guide/vercel.mdx
+++ b/src/content/docs/en/guides/integrations-guide/vercel.mdx
@@ -73,18 +73,12 @@ If you prefer to install the adapter manually instead, complete the following tw
You can deploy to different targets:
-* `edge`: SSR inside an [Edge function](https://vercel.com/docs/concepts/functions/edge-functions).
* `serverless`: SSR inside a [Node.js function](https://vercel.com/docs/concepts/functions/serverless-functions).
* `static`: generates a static website following Vercel's output formats, redirects, etc.
-:::note
-deploying to the Edge has [its limitations](https://vercel.com/docs/concepts/functions/edge-functions#known-limitations). An edge function can't be more than 1 MB in size and they don't support native Node.js APIs, among others.
-:::
-
You can change where to target by changing the import:
```js
-import vercel from '@astrojs/vercel/edge';
import vercel from '@astrojs/vercel/serverless';
import vercel from '@astrojs/vercel/static';
```
@@ -107,7 +101,7 @@ To configure this adapter, pass an object to the `vercel()` function call in `as
### analytics
**Type:** `boolean`
-**Available for:** Serverless, Edge, Static
+**Available for:** Serverless, Static
**Added in:** `@astrojs/vercel@3.1.0`
You can enable [Vercel Analytics](https://vercel.com/analytics) (including Web Vitals and Audiences) by setting `analytics: true`. This will inject Vercel’s tracking scripts into all your pages.
@@ -128,7 +122,7 @@ export default defineConfig({
### imagesConfig
**Type:** `VercelImageConfig`
-**Available for:** Edge, Serverless, Static
+**Available for:** Serverless, Static
**Added in:** `@astrojs/vercel@3.3.0`
Configuration options for [Vercel's Image Optimization API](https://vercel.com/docs/concepts/image-optimization). See [Vercel's image configuration documentation](https://vercel.com/docs/build-output-api/v3/configuration#images) for a complete list of supported parameters.
@@ -151,7 +145,7 @@ export default defineConfig({
### imageService
**Type:** `boolean`
-**Available for:** Edge, Serverless, Static
+**Available for:** Serverless, Static
**Added in:** `@astrojs/vercel@3.3.0`
When enabled, an [Image Service](/en/reference/image-service-reference/) powered by the Vercel Image Optimization API will be automatically configured and used in production. In development, a built-in Squoosh-based service will be used instead.
@@ -192,7 +186,7 @@ import astroLogo from '../assets/logo.png';
### includeFiles
**Type:** `string[]`
-**Available for:** Edge, Serverless
+**Available for:** Serverless
Use this property to force files to be bundled with your function. This is helpful when you notice missing files.
@@ -209,10 +203,6 @@ export default defineConfig({
});
```
-:::note
-When building for the Edge, all the dependencies get bundled in a single file to save space. **No extra file will be bundled**. So, if you *need* some file inside the function, you have to specify it in `includeFiles`.
-:::
-
### excludeFiles
**Type:** `string[]`
@@ -233,9 +223,11 @@ export default defineConfig({
});
```
-### Per-page functions
+### Function bundling configuration
-The Vercel adapter builds to a single function by default. Astro 2.7 added support for splitting your build into separate entry points per page. If you use this configuration the Vercel adapter will generate a separate function for each page. This can help reduce the size of each function so they are only bundling code used on that page.
+The Vercel adapter splits builds into a separate function per route by default. This helps reduce the size of each function, as it only bundles code used on that page.
+
+You can disable this and build to a single function by setting the `functionPerRoute` configuration option to `false`:
```js
// astro.config.mjs
@@ -244,10 +236,9 @@ import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
output: 'server',
- adapter: vercel(),
- build: {
- split: true,
- },
+ adapter: vercel({
+ functionPerRoute: false,
+ }),
});
```
@@ -286,7 +277,7 @@ You can use Vercel Edge middleware to intercept a request and redirect before se
The `@astrojs/vercel/serverless` adapter can automatically create the Vercel Edge middleware from an Astro middleware in your code base.
-This is an opt-in feature, and the `build.excludeMiddleware` option needs to be set to `true`:
+This is an opt-in feature, and the `edgeMiddleware` option needs to be set to `true`:
```js
// astro.config.mjs
@@ -294,10 +285,9 @@ import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel';
export default defineConfig({
output: 'server',
- adapter: vercel(),
- build: {
- excludeMiddleware: true,
- },
+ adapter: vercel({
+ edgeMiddleware: true,
+ }),
});
```
diff --git a/src/content/docs/en/guides/markdown-content.mdx b/src/content/docs/en/guides/markdown-content.mdx
index b4e9b0d231ddd..76db95a487c68 100644
--- a/src/content/docs/en/guides/markdown-content.mdx
+++ b/src/content/docs/en/guides/markdown-content.mdx
@@ -60,64 +60,6 @@ It probably isn't styled much, but Markdown does support:
📚 Read more about Astro's [file-based routing](/en/core-concepts/routing/) or options for creating [dynamic routes](/en/core-concepts/routing/#dynamic-routes).
-### Draft Pages
-
-`draft: true` is an optional frontmatter value that will mark an individual Markdown or MDX page or post as "unpublished." By default, this page will be:
-- excluded from the site build (**no page will be built**)
-- returned by [`Astro.glob()`](/en/reference/api-reference/#astroglob) (**visible in lists of posts**)
-
-```markdown {5}
----
-# src/pages/post/blog-post.md
-layout: ../../layouts/BaseLayout.astro
-title: My Blog Post
-draft: true
----
-
-This is my in-progress blog post.
-
-No page will be built for this post.
-
-To build and publish this post:
-
-- update the frontmatter to `draft: false` or
-- remove the `draft` property entirely.
-
-But, this page _will_ be returned by any matching `Astro.glob()` request.
-```
-
-To exclude draft posts from being included in a post archive, or list of most recent posts, you can filter the results returned by `Astro.glob()`:
-
-```js
-const posts = await Astro.glob('../pages/post/*.md');
-const nonDraftPosts = posts.filter((post) => !post.frontmatter.draft);
-```
-
-:::note[Using content collections?]
-This feature is not supported for content collections, however you can use a [collection query filter](/en/guides/content-collections/#filtering-collection-queries) to filter your draft posts.
-:::
-
-#### Enable building draft pages
-
-To enable building draft pages by default, update `astro.config.mjs` by adding `drafts: true` to `markdown` or to the `mdx` integration:
-
-```js title="astro.config.mjs" ins={5, 8}
-import { defineConfig } from 'astro/config';
-
-export default defineConfig({
- markdown: {
- drafts: true,
- },
- integrations: [mdx({
- drafts: true,
- })],
-});
-```
-
-:::tip
-You can also pass the `--drafts` flag when running `astro build` to build draft pages!
-:::
-
## Markdown Features
Astro provides some extra, built-in Markdown features available when using Markdown and MDX files.
@@ -187,7 +129,7 @@ For example, to prevent `<` being interpreted as the beginning of an HTML elemen
Adding the Astro [MDX integration](/en/guides/integrations-guide/mdx/) enhances your Markdown authoring with JSX variables, expressions and components.
-It also adds extra features to standard MDX, including support for [Markdown-style frontmatter in MDX](https://mdxjs.com/guides/frontmatter/). This allows you to use most of Astro's built-in Markdown features like a [frontmatter `layout`](#frontmatter-layout) property and a setting for [draft pages](#draft-pages).
+It also adds extra features to standard MDX, including support for [Markdown-style frontmatter in MDX](https://mdxjs.com/guides/frontmatter/). This allows you to use most of Astro's built-in Markdown features like a [frontmatter `layout`](#frontmatter-layout) property.
`.mdx` files must be written in [MDX syntax](https://mdxjs.com/docs/what-is-mdx/#mdx-syntax) rather than Astro’s HTML-like syntax.
diff --git a/src/content/docs/en/guides/middleware.mdx b/src/content/docs/en/guides/middleware.mdx
index d7a6688a4c8b0..4657879ff0a8d 100644
--- a/src/content/docs/en/guides/middleware.mdx
+++ b/src/content/docs/en/guides/middleware.mdx
@@ -45,7 +45,7 @@ You can import and use the utility function `defineMiddleware()` to take advanta
```ts
// src/middleware.ts
-import { defineMiddleware } from "astro/middleware";
+import { defineMiddleware } from "astro:middleware";
// `context` and `next` are automatically typed
export const onRequest = defineMiddleware((context, next) => {
@@ -137,7 +137,7 @@ export const onRequest = async (context, next) => {
Multiple middlewares can be joined in a specified order using [`sequence()`](#sequence):
```js title="src/middleware.js"
-import { sequence } from "astro/middleware";
+import { sequence } from "astro:middleware";
async function validation(_, next) {
console.log("validation request");
@@ -218,4 +218,4 @@ This function can be used by integrations/adapters to programmatically execute t
### `trySerializeLocals`
-A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.
\ No newline at end of file
+A low-level API that takes in any value and tries to return a serialized version (a string) of it. If the value cannot be serialized, the function will throw a runtime error.
diff --git a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx
index 2e7e82bd866e2..9496bc43dbbd3 100644
--- a/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx
+++ b/src/content/docs/en/guides/migrate-to-astro/from-gatsby.mdx
@@ -87,8 +87,6 @@ You may find it useful to install some of [Astro's optional integrations](/en/gu
- **@astrojs/react**: to reuse some existing React UI components in your new Astro site or keep writing with React components.
-- **@astrojs/image**: to replace Gatsby's Image plugin with Astro's own image-optimizing components. (Experimental: works in `.astro` and `.mdx` files only.)
-
- **@astrojs/mdx**: to bring existing MDX files from your Gatsby project, or to use MDX in your new Astro site.
@@ -321,36 +319,29 @@ See more about [Styling in Astro](/en/guides/styling/).
### Gatsby Image Plugin to Astro
-:::note
-Astro v3.0 will include a new `astro:assets` module and will deprecate the existing `@astrojs/image` integration.
-
-Access to `astro:assets` is currently available under an experimental flag, and is the recommended way to begin a new Astro project. If you are migrating to Astro pre-v3.0, we recommend [enabling the experimental flag to use assets](/en/guides/assets/) as an image solution.
-:::
-
-Convert Gatsby's `` and `` components with [Astro's own image integration components](/en/guides/images/#astros-image-integration), or with a standard HTML `` / JSX `` tag as appropriate.
+Convert Gatsby's `` and `` components to [Astro's own image integration components](/en/guides/images/#image--astroassets), or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
-Astro's `` and `` components are experimental and currently work in `.astro` and `.mdx` files only. See a [full list of component attributes](/en/guides/integrations-guide/image/#usage) available for these components, and note that several will differ from Gatsby's attributes.
+Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Gatsby's attributes.
-To continue using local images in Markdown (`.md`) files using standard Markdown syntax (`![]()`), move your images into your `public/` folder. You may need to update the link to the relative URL. You can also use the standard `` tag in these files. Note that these [images in `public/` will not be optimized by Astro](/en/guides/images/#public).
+To continue using [images in Markdown (`.md`) files](/en/guides/images/#images-in-markdown-files) using standard Markdown syntax (`![]()`), you may need to update the link. Using the HTML `` tag directy is not supported in `.md` files for local images, and must be converted to Markdown syntax.
```md
# My Markdown Page
-
-
-
+
+
+
```
In React (`.jsx`) components, use standard JSX image syntax (``). Astro will not optimize these images, but you can install and use NPM packages for more flexibility.
diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx
index 20b13d4dfa781..6dfd7798e88d8 100644
--- a/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx
+++ b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx
@@ -83,8 +83,6 @@ You may find it useful to install some of [Astro's optional integrations](/en/gu
- **@astrojs/react**: to reuse some existing React UI components in your new Astro site, or keep writing with React components.
-- **@astrojs/image**: to replace Next's Image plugin with Astro's own image-optimizing components. (Experimental: works in `.astro` and `.mdx` files only.)
-
- **@astrojs/mdx**: to bring existing MDX files from your Next project, or to use MDX in your new Astro site.
### Put your source code in `src`
@@ -419,22 +417,17 @@ See more about [Styling in Astro](/en/guides/styling/).
### Next Image Plugin to Astro
-:::note
-Astro v3.0 will include a new `astro:assets` module and will deprecate the existing `@astrojs/image` integration.
-
-Access to `astro:assets` is currently available under an experimental flag, and is the recommended way to begin a new Astro project. If you are migrating to Astro pre-v3.0, we recommend [enabling the experimental flag to use assets](/en/guides/assets/) as an image solution.
-:::
+Convert any Next `` components to [Astro's own image component](/en/guides/images/#image--astroassets) in `.astro` or `.mdx` files, or to a [standard HTML `` / JSX ``](/en/guides/images/#images-in-ui-framework-components) tag as appropriate in your React components.
-Convert any Next `` components with [Astro's own image integration components](/en/guides/images/#astros-image-integration), or with a standard HTML ``. See a [full list of component attributes](/en/guides/integrations-guide/image/#usage) available for Astro's `` and `` components, and note that several will differ from Next's attributes.
+Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Next's attributes.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
In React (`.jsx`) components, use standard JSX image syntax (``). Astro will not optimize these images, but you can install and use NPM packages for more flexibility.
diff --git a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx
index 296ed93cf8930..d95736d2148ca 100644
--- a/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx
+++ b/src/content/docs/en/guides/migrate-to-astro/from-nuxtjs.mdx
@@ -85,8 +85,6 @@ You may find it useful to install some of [Astro's optional integrations](/en/gu
- **@astrojs/vue**: to reuse some existing Vue UI components in your new Astro site, or keep writing with Vue components.
-- **@astrojs/image**: to replace Nuxt's Image plugin with Astro's own image-optimizing components.
-
- **@astrojs/mdx**: to bring existing MDX files from your Nuxt project, or to use MDX in your new Astro site.
### Put your source code in `src`
@@ -489,24 +487,17 @@ See more about [Styling in Astro](/en/guides/styling/).
### Nuxt Image Plugin to Astro
-:::note
-Astro v3.0 will include a new `astro:assets` module and will deprecate the existing `@astrojs/image` integration.
-
-Access to `astro:assets` is currently available under an experimental flag, and is the recommended way to begin a new Astro project. If you are migrating to Astro pre-v3.0, we recommend [enabling the experimental flag to use assets](/en/guides/assets/) as an image solution.
-:::
-
-Convert any [Nuxt `` or `` components](https://image.nuxtjs.org/components/nuxt-img) to [Astro's own image integration components](/en/guides/images/#astros-image-integration), or to a standard HTML `` tag.
+Convert any [Nuxt `` or `` components](https://image.nuxtjs.org/components/nuxt-img) to [Astro's own image component](/en/guides/images/#image--astroassets) in `.astro` or `.mdx` files, or to a [standard HTML ``](/en/guides/images/#images-in-ui-framework-components) or `` tag as appropriate in your Vue components.
-See a [full list of component attributes](/en/guides/integrations-guide/image/#usage) available for Astro's `` and `` components, and note that several will differ from Nuxt's attributes.
+Astro's `` component works in `.astro` and `.mdx` files only. See a [full list of its component attributes](/en/guides/images/#properties) and note that several will differ from Nuxt's attributes.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
In Vue (`.vue`) components within your Astro app, use standard JSX image syntax (``). Astro will not optimize these images, but you can install and use NPM packages for more flexibility.
diff --git a/src/content/docs/en/guides/rss.mdx b/src/content/docs/en/guides/rss.mdx
index ed5d221fc82fb..20915062a0dd8 100644
--- a/src/content/docs/en/guides/rss.mdx
+++ b/src/content/docs/en/guides/rss.mdx
@@ -47,7 +47,7 @@ The example file below `src/pages/rss.xml.js` will create an RSS feed at `site/r
```js title="src/pages/rss.xml.js"
import rss from '@astrojs/rss';
-export function get(context) {
+export function GET(context) {
return rss({
// `` field in output xml
title: 'Buzz’s Blog',
@@ -81,7 +81,7 @@ To create an RSS feed of pages managed in [content collections](/en/guides/conte
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
-export async function get(context) {
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Buzz’s Blog',
@@ -128,7 +128,7 @@ This function assumes, but does not verify, that all necessary feed properties a
```js title="src/pages/rss.xml.js" "pagesGlobToRssItems" "await pagesGlobToRssItems("
import rss, { pagesGlobToRssItems } from '@astrojs/rss';
-export async function get(context) {
+export async function GET(context) {
return rss({
title: 'Buzz’s Blog',
description: 'A humble Astronaut’s guide to the stars',
@@ -166,7 +166,7 @@ import sanitizeHtml from 'sanitize-html';
import MarkdownIt from 'markdown-it';
const parser = new MarkdownIt();
-export async function get(context) {
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Buzz’s Blog',
@@ -188,7 +188,7 @@ When using glob imports with Markdown, you may use the `compiledContent()` helpe
import rss from '@astrojs/rss';
import sanitizeHtml from 'sanitize-html';
-export function get(context) {
+export function GET(context) {
const postImportResult = import.meta.glob('../posts/**/*.md', { eager: true });
const posts = Object.values(postImportResult);
return rss({
diff --git a/src/content/docs/en/guides/server-side-rendering.mdx b/src/content/docs/en/guides/server-side-rendering.mdx
index 7b225bf73cb61..89a06dd874257 100644
--- a/src/content/docs/en/guides/server-side-rendering.mdx
+++ b/src/content/docs/en/guides/server-side-rendering.mdx
@@ -172,7 +172,7 @@ And for an endpoint:
```js title="src/pages/myendpoint.js" {1}
export const prerender = true;
-export async function get() {
+export async function GET() {
return {
body: JSON.stringify({ message: `This is my static endpoint` }),
};
@@ -186,7 +186,7 @@ For a mostly static site configured as `output: hybrid`, add `export const prere
```js title="src/pages/randomnumber.js" {1}
export const prerender = false;
-export async function get() {
+export async function GET() {
let number = Math.random();
return {
body: JSON.stringify({ number, message: `Here's a random number: ${number}` }),
diff --git a/src/content/docs/en/guides/styling.mdx b/src/content/docs/en/guides/styling.mdx
index 129240181a1e8..19bc77b32f38b 100644
--- a/src/content/docs/en/guides/styling.mdx
+++ b/src/content/docs/en/guides/styling.mdx
@@ -41,11 +41,11 @@ This CSS:
Compiles to this:
```astro
@@ -159,8 +159,7 @@ import MyComponent from "../components/MyComponent.astro"
This will be red!
```
-This pattern lets you style child components directly. Astro will pass the parent’s scoped class name (e.g. `astro-HHNQFKH6`) through the `class` prop automatically, including the child in its parent’s scope.
-
+This pattern lets you style child components directly. Astro will pass the parent’s scoped class name (e.g. `astro-hhnqfkh6`) through the `class` prop automatically, including the child in its parent’s scope. Note this pattern only works when your [`scopedStyleStrategy` option](/en/reference/configuration-reference/#scopedstylestrategy) is either `'where'` or `'class'`.
:::note[Scoped classes from parent components]
Because the `class` prop includes the child in its parent’s scope, it is possible for styles to cascade from parent to child. To avoid this having unintended side effects, ensure you use unique class names in the child component.
:::
@@ -531,24 +530,36 @@ If you are using Tailwind, the [typography plugin](https://tailwindcss.com/docs/
### Bundle control
-When Astro builds your site for production deployment it combines your CSS into chunks. Each page on your site is its own chunk, and additionally, CSS that is shared between multiple pages is further split off into their own chunks for reuse.
+When Astro builds your site for production deployment, it minifies and combines your CSS into chunks. Each page on your site gets its own chunk, and additionally, CSS that is shared between multiple pages is further split off into their own chunks for reuse.
+
+However, when you have several pages sharing styles, some shared chunks can become really small. If all of them were sent separately, it would lead to many stylesheets requests and affect site performance. Therefore, by default Astro will link only those in your HTML above 4kB in size as `` tags, while inlining smaller ones into `
+```
+
+### Removed: automatic flattening of `getStaticPaths()`'s return value
+
+In Astro v2.x, the return value of [`getStaticPaths()`](/en/reference/api-reference/#getstaticpaths) was automatically flattened to allow you to return an array of arrays without errors.
+
+Astro v3.0 removes automatic flattening of `getStaticPaths()`'s result.
+
+#### What should I do?
+
+If you're returning an array of arrays instead of an array of _objects_ (as is expected), `.flatMap` and `.flat` should now be used to ensure that you are returning a flat array.
+
+An [error message indicating that `getStaticPath()`'s return value must be an array of objects](/en/reference/errors/invalid-get-static-paths-entry/#what-went-wrong) will be provided if you need to update your code.
+
+### Moved: `astro check` now requires an external package
+
+In Astro v2.x, [`astro check`](/en/reference/cli-reference/#astro-check) was included in Astro by default, and its dependencies were bundled in Astro. This meant a larger package whether or not you ever used `astro check`. This also prevented you from having control over the version of TypeScript and the Astro Language Server to use.
+
+
+Astro v3.0 moves the `astro check` command out of Astro core and now requires an external package `@astrojs/check`. Additionally, you must install `typescript` in your project to use the `astro check` command.
+
+#### What should I do?
+
+Run the `astro check` command after upgrading to Astro v3.0 and follow the prompts to install the required dependencies, or manually install `@astrojs/check` and `typescript` into your project.
+
+### Deprecated: `build.excludeMiddleware` and `build.split`
+
+In Astro v2.x, `build.excludeMiddleware` and `build.split` were used to change how specific files were emitted when using an adapter in SSR mode.
+
+Astro v3.0 replaces these build config options with new [SSR adapter configuration options](/en/guides/integrations-guide/#official-integrations) to perform the same tasks: `edgeMiddleware` and `functionPerRoute`.
+
+#### What should I do?
+
+Update the Astro config file to now use the new options **in the adapter configuration** directly.
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import vercel from "@astrojs/vercel/serverless";
+
+export default defineConfig({
+ build: {
+ excludeMiddleware: true
+ },
+ adapter: vercel({
+ edgeMiddleware: true
+ }),
+});
+```
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import netlify from "@astrojs/netlify/functions";
+
+export default defineConfig({
+ build: {
+ split: true
+ },
+ adapter: netlify({
+ functionPerRoute: true
+ }),
+});
+```
+
+### Deprecated: `markdown.drafts`
+
+In Astro v2.x, the `markdown.drafts` configuration allowed you to have draft pages that were available in when running the dev server, but not built in production.
+
+Astro v3.0 deprecates this feature in favor of the content collections method of handling draft pages by filtering manually instead, which gives more control over the feature.
+
+#### What should I do?
+
+To continue to mark some pages in your project as drafts, [migrate to content collections](/en/guides/content-collections/#migrating-from-file-based-routing) and [manually filter out pages](/en/guides/content-collections/#filtering-collection-queries) with the `draft: true` frontmatter property instead.
+
+### Deprecated: returning simple object in endpoints
+
+In Astro v2.x, endpoints could return a simple object, which would be converted to a JSON response.
+
+Astro v3.0 deprecates this behavior in favor of returning a `Response` object directly.
+
+#### What should I do?
+
+Update your endpoints to return a `Response` object directly.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "title": "Bob's blog" }};
+ return new Response(JSON.stringify({ "title": "Bob's blog" }));
+}
+```
+
+If you really need to keep the previous format, you can use the `ResponseWithEncoding` object but will be deprecated in the future.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "title": "Bob's blog" } };
+ return new ResponseWithEncoding({ body: { "title": "Bob's blog" }});
+}
+```
+
+### Changed default: port `3000`
+
+In Astro v2.x, Astro ran on port `3000` by default.
+
+Astro v3.0 changes the [default port](/en/reference/cli-reference/#--port-number) to `4321`. 🚀
+
+#### What should I do?
+
+Update any existing references to `localhost:3000`, for example in tests or in your `README`, to reflect the new port `localhost:4321`.
+
+
+### Changed default: import.meta.env.BASE_URL `trailingSlash`
+
+In Astro v2.x, `import.meta.env.BASE_URL` appended your [`base`](/en/reference/configuration-reference/#base) setting with a [trailingSlash](/en/reference/configuration-reference/#trailingslash) by default. `trailingSlash: "ignore"` also appended a trailing slash.
+
+Astro v3.0 no longer appends `import.meta.env.BASE_URL` with a trailing slash by default, nor when `trailingSlash: "ignore"` is set. (The existing behavior of `base` in combination with `trailingSlash: "always"` or `trailingSlash: "never"` is unchanged.)
+
+#### What should I do?
+
+If your `base` already has a trailing slash, no change is needed.
+
+If your `base` does not have a trailing slash, add one if you wish to preserve the previous default (or `trailingSlash: "ignore"`) behavior:
+
+```js title="astro.config.mjs" del={4} ins={5}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ base: 'my-base',
+ base: 'my-base/',
+});
+```
+
+### Changed default: `compressHTML`
+
+In Astro v2.x, Astro only compressed your emitted HTML when [`compressHTML`](/en/reference/configuration-reference/#compresshtml) was explicitly set to `true`. The default value was `false`.
+
+Astro v3.0 now compresses emitted HTML by default.
+
+#### What should I do?
+
+You can now remove `compressHTML: true` from your configuration as this is the new default behavior.
+
+```js title="astro.config.mjs" del={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ compressHTML: true
+})
+```
+
+You must now set `compressHTML: false` to opt out of HTML compression.
+
+### Changed default: `scopedStyleStrategy`
+
+In Astro v2.x, the default value of [`scopedStyleStrategy`](/en/reference/configuration-reference/#scopedstylestrategy) was `"where"`.
+
+Astro v3.0 introduces a new, default value: `"attribute"`. By default, styles are now applied using `data-*` attributes.
+
+#### What should I do?
+
+To retain your project's current [style scoping](/en/guides/styling/#scoped-styles), update the configuration file to the previous default value:
+
+
+```js title="astro.config.mjs" ins={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ scopedStyleStrategy: "where"
+})
+```
+
+### Changed default: `inlineStyleSheets`
+
+In Astro v2.x, all project stylesheets were sent as link tags by default. You could opt in to inlining them into `
+```
+
+### ``
+
+La [sintaxis de Astro](/es/core-concepts/astro-syntax/) también admite escribir directamente una etiqueta ``, con control total sobre su salida final. Estas imágenes no se procesarán ni optimizarán.
+
+Esta acepta todas las propiedades de la etiqueta HTML ``, y la única propiedad requerida es `src`.
+
+#### Imágenes locales en `src/`
+
+Las imágenes locales deben ser **importadas desde la ruta relativa** al archivo `.astro` existente, o configurar y usar un [alias de importación](/es/guides/aliases/). Luego, puedes acceder a la propiedad `src` de la imagen y otras propiedades para usar en la etiqueta ``.
+
+Por ejemplo, utiliza las propiedades `height` y `width` propias de la imagen para evitar CLS y mejorar los Core Web Vitals.
+
+```astro "myDog.width" "myDog.height"
+---
+// importar imágenes locales
+import myDog from `../../images/pets/local-dog.jpg`
+---
+// acceder a las propiedades de la imagen
+
+```
+
+Los activos de imagen importados coinciden con la siguiente firma:
+
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
+
+#### Imágenes en `public/`
+
+Para las imágenes ubicadas dentro de `public/`, utiliza la **ruta de archivo relativa a la carpeta public** de la imagen como valor de `src`:
+
+```astro '"/images/public-cat.jpg"'
+
+```
+
+#### Imágenes remotas
+
+Para las imágenes remotas, utiliza la **URL completa** de la imagen como valor de `src`:
+
+```astro '"https://example.com/remote-cat.jpg"'
+
+```
+
+### Eligiendo `` vs ``
+
+El componente `` optimiza tu imagen e infiere el ancho y el alto (en imágenes locales) en función de la relación de aspecto original para evitar CLS. Sin embargo, solo funciona con ciertos formatos y no proporciona un elemento ``, ni admite `srcset`.
+
+Utiliza el elemento HTML `` cuando no puedas usar el componente ``, por ejemplo:
+ - para formatos de imagen no admitidos
+ - cuando no deseas que tu imagen se optimice mediante Astro
+ - para acceder y cambiar el atributo `src` dinámicamente en el lado del cliente
+
+### Autorizando imágenes remotas
+
+Puedes configurar listas de dominios y patrones de URL de origen de imágenes autorizados para la optimización de imágenes utilizando [`image.domains`](/es/reference/configuration-reference/#imagedomains) y [`image.remotePatterns`](/es/reference/configuration-reference/#imageremotepatterns). Esta configuración es una capa adicional de seguridad para proteger tu sitio al mostrar imágenes desde una fuente externa.
+
+Remote images from other sources will not be optimized, but using the `` component for these images will prevent Cumulative Layout Shift (CLS).
+
+For example, the following configuration will only allow remote images from `astro.build` to be optimized:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ domains: ["astro.build"],
+ }
+});
+```
+
+La siguiente configuración solo permitirá que las imágenes remotas provengan de hosts HTTPS:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ remotePatterns: [{ protocol: "https" }],
+ }
+});
+```
+
+## Utilizando imágenes de un CMS o CDN
+
+Los CDNs de imágenes funcionan con todas las opciones de imágenes de Astro. Utiliza la URL completa de la imagen como atributo `src` en el componente ``, una etiqueta `` o en la notación Markdown. Para la optimización de imágenes con imágenes remotas, también [configura tus dominios autorizados o patrones de URL](#autorizando-imágenes-remotas).
+
+Alternativamente, si el CDN proporciona un SDK de Node.js, puedes utilizarlo en tu proyecto. Por ejemplo, el SDK de [Cloudinary](https://cloudinary.com/documentation/node_integration) puede generar una etiqueta `` con el `src` adecuado por ti.
+
+## Imágenes en archivos Markdown
+
+Utiliza la sintaxis estándar de Markdown `` en tus archivos `.md`. Esta sintaxis funciona con la [API de servicio de imagenes](/es/reference/image-service-reference/) de Astro para optimizar tus imágenes locales y las imágenes remotas autorizadas.
```md
# Mi página Markdown
-
-
-
+
+
+
+
+
+
+
-
-
+
+
```
-### En archivos MDX
+La etiqueta `` no es compatible para imágenes locales y el componente `` no está disponible en archivos `.md`.
-Puedes usar la sintaxis estándar de Markdown `![]()` o las etiquetas JSX `` en tus archivos `.mdx`. Al igual que los archivos Markdown, los archivos MDX pueden mostrar imágenes desde tu carpeta `public/` o un servidor remoto.
+Si necesitas más control sobre los atributos de tus imágenes, te recomendamos utilizar el formato de archivo `.mdx`, que te permite incluir el componente `` de Astro o una etiqueta JSX `` además de la sintaxis Markdown. Utiliza la [integración MDX](/es/guides/integrations-guide/mdx/) para agregar soporte para MDX en Astro.
-Además, puedes importar y usar imágenes ubicadas en el directorio `src/` de tu proyecto, como lo harías en los componentes de Astro.
+## Imágenes en archivos MDX
-```mdx
-// src/pages/post-1.mdx
+Puedes utilizar el componente `` de Astro y las etiquetas JSX `` en tus archivos `.mdx` importando tanto el componente como tu imagen. Úsalos tal como se [utilizan en archivos `.astro`](#imágenes-en-archivos-astro).
-import rocket from '../images/rocket.svg';
+Además, hay soporte para la [sintaxis estándar de Markdown ``](#imágenes-en-archivos-markdown) sin necesidad de importación.
+
+```mdx title="src/pages/post-1.mdx"
+---
+title: Título de mi página
+---
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
-# Mi página MDX
+# Mi Página MDX
-// Imagen local almacenada en src/images/rocket.svg
-
+// Imagen local almacenada en src/assets/
+
+
+
-// Imagen local almacenada en public/assets/stars.png
-
-
+// Imagen almacenada en public/images/
+
+
+
// Imagen remota en otro servidor
-
-
+
+
+
+
```
-### En componentes de un framework de UI
+## Imágenes en Colecciones de Contenido
-Cuando agregues imágenes en un [componente de un framework de UI](/es/core-concepts/framework-components/) (ej. React, Svelte), usa la sintaxis de imágenes apropiada para ese framework en particular.
+Puedes declarar una imagen asociada para una entrada de colecciones de contenido, como la imagen de portada de una entrada de blog, en tu metadatos utilizando su ruta relativa a la carpeta actual:
-## Dónde almacenar imágenes
+```md title="src/content/blog/my-post.md" {3}
+---
+title: "Mi primera entrada en el blog"
+cover: "./firstpostcover.jpeg" # se resolverá como "src/content/blog/firstblogcover.jpeg"
+coverAlt: "Una fotografía de una puesta de sol detrás de una cordillera."
+---
+
+Esta es una entrada de blog
+```
+
+El helper `image` para el esquema de colecciones de contenido te permite validar los metadatos de la imagen utilizando Zod.
+
+```ts title="src/content/config.ts"
+import { defineCollection, z } from "astro:content";
+
+const blogCollection = defineCollection({
+ schema: ({ image }) => z.object({
+ title: z.string(),
+ cover: image().refine((img) => img.width >= 1080, {
+ message: "¡La imagen de portada debe tener al menos 1080 píxeles de ancho!",
+ }),
+ coverAlt: z.string(),
+ }),
+});
+
+export const collections = {
+ blog: blogCollection,
+};
+```
+
+La imagen se importará y transformará en metadatos, lo que te permitirá pasarlo como `src` a ``, `` o `getImage()`.
+
+El siguiente ejemplo muestra una página de índice de un blog que muestra la foto de portada y el título de cada entrada del blog a partir del esquema anterior:
+
+```astro title="src/pages/blog.astro" {10}
+---
+import { Image } from "astro:assets";
+import { getCollection } from "astro:content";
+const allBlogPosts = await getCollection("blog");
+---
+
+{
+ allBlogPosts.map((post) => (
+
+ ))
+}
+```
+
+## Imágenes en componentes de frameworks UI
+
+Cuando añadas imágenes en un componente de un framework UI, utiliza la sintaxis de imagen propia del framework para renderizar una imagen (p. ej. `` en JSX, `` en Svelte).
+
+Las imágenes locales deben **ser importadas primero** para acceder a sus [propiedades de imagen](#imágenes-locales-en-src) como `src`.
+
+```jsx title="src/components/ReactImage.jsx"
+import stars from "../assets/stars.png"
+
+export default function ReactImage () {
+ return (
+
+ )
+}
+```
+
+```svelte title="src/components/SvelteImage.svelte"
+
+
+
+
+```
-### `src/`
+#### Pasando el componente Image
-Tus imágenes almacenadas en `src/` pueden ser usadas por otros componentes (`.astro`, `.mdx` y otros frameworks), pero no en archivos de Markdown.
+El componente ``, al igual que cualquier otro componente de Astro, **no está disponible para los componentes de frameworks UI**.
-Nostros recomendamos que mantengas tus imágenes en [`public/`](#public) o almacenarlas [remotamente](#usar-imágenes-de-un-cms-o-una-cdn) si tu necesitas usar archivos de Markdown.
+Sin embargo, puedes pasar el contenido estático generado por `` a un componente de framework dentro de un archivo `.astro` como hijos o utilizando un [`` nombrado](/es/core-concepts/framework-components/#puedo-usar-componentes-de-astro-dentro-de-mis-componentes-de-framework):
-Impórtalas desde una **ruta relativa** o un [alias de importación](/es/guides/aliases/) en cualquier archivo de componente y después usa la importación como un atributo `src` de imagen.
+
+```astro title="ImageWrapper.astro"
+---
+import ReactComponent from './ReactComponent.jsx';
+import { Image } from "astro:assets"
+import stars from "~/stars/docline.png";
+---
+
+
+
+
+```
+
+## Generando imágenes con `getImage()`
+
+:::caution
+`getImage()` se basa en APIs solo para el servidor y provoca errores en la compilación cuando se utiliza en el lado del cliente.
+:::
+
+La función `getImage()` está destinada a generar imágenes que se utilizarán en otro lugar que no sea directamente en HTML, por ejemplo, en una [Ruta API](/es/core-concepts/endpoints/#endpoints-del-servidor-rutas-de-api). También te permite crear tu propio componente `` personalizado.
+
+`getImage()` recibe un objeto de opciones con las [mismas propiedades que el componente Image](#propiedades) (excepto `alt`).
```astro
---
-// src/pages/index.astro
+import { getImage } from "astro:assets";
+import myBackground from "../background.png"
-// Acceso a imágenes en `src/images/`
-import logo from '../images/logo.png';
+const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
-
+
+
```
-### `public/`
+Devuelve un objeto con las siguientes propiedades:
-Tus imágenes pueden ser almacenadas en `src/` y pueden ser usadas por otros componentes (`.astro`, `.mdx` y otros frameworks UI), pero no en archivos de Markdown.
+```js
+{
+ options: {...} // Parámetros originales pasados
+ src: "https//..." // Ruta a la imagen generada
+ attributes: {...} // Atributos HTML adicionales necesarios para representar la imagen (width, height, style, etc..)
+}
+```
-Sin embargo, los archivos en el directorio `/public` son siempre servidos o copiados sin modificaciones. Si estás usando imágenes fuera de los archivos de Markdown, te recomendamos que las imágenes locales sean guardadas en `/src` cuando sea posible para que Astro pueda transformarlas, optimizarlas y empaquetarlas.
+## Texto Alt
-El atributo `src` es **relativo a la carpeta public**. En Markdown, también puedes usar la notación `![]()`.
+No todos los usuarios pueden ver las imágenes de la misma manera, por lo que la accesibilidad es una preocupación especialmente importante al utilizar imágenes. Utiliza el atributo `alt` para proporcionar [texto alternativo descriptivo](https://www.w3.org/WAI/tutorials/images/) para las imágenes.
-```astro title="src/pages/index.astro"
+Este atributo es obligatorio para el componente ``. `` lanzará un error si no se proporciona texto alternativo.
+
+Si la imagen es meramente decorativa (es decir, no contribuye a la comprensión de la página), establece `alt=""` para que los lectores de pantalla sepan que deben ignorar la imagen.
+
+## Servicio de imágenes por defecto
+
+[Sharp](https://github.com/lovell/sharp) es el servicio de imágenes por defecto utilizado para `astro:assets`.
+
+Si prefieres utilizar [Squoosh](https://github.com/GoogleChromeLabs/squoosh) para transformar tus imágenes, actualiza tu configuración con lo siguiente:
+
+```js title="astro.config.mjs" ins={4-6}
+import { defineConfig, squooshImageService } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+});
+```
+
+## Integraciones comunitarias
+
+Existen varias [integraciones de imágenes de la comunidad](https://astro.build/integrations?search=images) de terceros para optimizar y trabajar con imágenes en tu proyecto de Astro.
+
+## Actualizar a v3.0 desde v2.x
+
+`astro:assets` ya no está detrás de una bandera experimental en Astro v3.0.
+
+`` es ahora un componente integrado y se ha eliminado la integración anterior `@astrojs/image`.
+
+Estos y otros cambios relacionados con el uso de imágenes en Astro pueden causar algunos cambios disruptivos al actualizar tu proyecto de Astro de una versión anterior.
+
+Sigue las instrucciones a continuación según corresponda para actualizar un proyecto de Astro v2.x a v3.0.
+
+### Actualizar desde `experimental.assets`
+
+Si habías habilitado previamente la bandera experimental para `astro:assets`, deberás actualizar tu proyecto para Astro v3.0, que ahora incluye las características de assets de forma predeterminada.
+
+#### Eliminar la bandera `experimental.assets`
+
+Elimina la bandera experimental:
+
+```js title="astro.config.mjs" del={4-6}
+import { defineConfig } from 'astro/config';
+
+export default defineConfig({
+ experimental: {
+ assets: true
+ }
+});
+```
+
+Si es necesario, también actualiza tu archivo `src/env.d.ts` para reemplazar la referencia `astro/client-image` por `astro/client`:
+
+```ts title="src/env.d.ts" del={1} ins={2}
+///
+///
+```
+
+#### Eliminar el alias de importación `~/assets`
+
+Este alias de importación ya no se incluye por defecto con `astro:assets`. Si estabas usando este alias con assets experimentales, debes convertirlos a rutas de archivo relativas o [crear tus propios alias de importación](/es/guides/aliases/).
+
+```astro title="src/pages/posts/post-1.astro" del={2} ins={3}
+---
+import rocket from '~/assets/rocket.png'
+import rocket from '../../assets/rocket.png';
---
+```
+
+#### Agrega soporte sencillo para assets en Cloudflare, Deno, Vercel Edge y Netlify Edge
+
+ Astro v3.0 permite que `astro:assets` funcione sin errores en Cloudflare, Deno, Vercel Edge y Netlify Edge, que no admiten la optimización de imágenes integrada de Astro con Squoosh y Sharp. Ten en cuenta que Astro no realiza ninguna transformación ni procesamiento de imágenes en estos entornos. Sin embargo, aún puedes disfrutar de otros beneficios de usar `astro:assets`, como la ausencia de Desplazamiento Acumulativo de Diseño (CLS), el atributo `alt` obligatorio y una experiencia de autoría coherente.
+
+ Si antes evitaste usar `astro:assets` debido a estas limitaciones, ahora puedes usarlo sin problemas. Puedes configurar el servicio de imágenes sin acción para optar explícitamente por este comportamiento:
+
+```js title="astro.config.mjs" ins={4-8}
+import { defineConfig } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: {
+ entrypoint: 'astro/assets/services/noop'
+ }
+ }
+});
+```
+
+### Decide dónde almacenar tus imágenes
+
+Consulta la guía de Imágenes para ayudarte a decidir [dónde almacenar tus imágenes](#dónde-guardar-las-imágenes). Es posible que desees aprovechar las nuevas opciones para almacenar tus imágenes con la flexibilidad adicional que `astro:assets` ofrece. Por ejemplo, las imágenes relativas desde la carpeta `src/` de tu proyecto ahora pueden ser referenciadas en Markdown, MDX y Markdoc utilizando la sintaxis estándar de Markdown ``.
+
+### Actualiza las etiquetas existentes ``
-// Acceso a imágenes en `public/images/`
+Anteriormente, importar una imagen devolvía un `string` con la ruta de la imagen. Los assets de imagen importados coinciden con la siguiente firma:
+
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
+
+Debes actualizar el atributo `src` de cualquier etiqueta `` existente (incluyendo cualquier [imagen en componentes de frameworks UI](#imágenes-en-componentes-de-frameworks-ui)) y también puedes actualizar otros atributos que ahora están disponibles para ti a partir de la imagen importada.
+
+```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={4} ins={6}
---
-
+import rocket from '../images/rocket.svg';
+---
+
+
+
```
-## Integración Image de Astro
+### Actualiza tus archivos Markdown, MDX y Markdoc
-:::note[para ser archivada en la versión v3.0]
-La integración [`@astrojs/image`](https://github.com/withastro/astro/tree/main/packages/integrations/image) ya no será compatible activamente en la versión de Astro v3.0.
+Las imágenes relativas desde la carpeta `src/` de tu proyecto ahora pueden ser referenciadas en Markdown, MDX y Markdoc utilizando la sintaxis estándar de Markdown ``.
-Te sugerimos que la elimines lo antes posible y que uses el módulo experimental `astro:assets` que se integrará en `astro@3.0`.
+Esto te permite mover tus imágenes desde el directorio `public/` a la carpeta `src/` de tu proyecto, donde ahora serán procesadas y optimizadas. Tus imágenes existentes en `public/` y las imágenes remotas siguen siendo válidas, pero no son optimizadas por el proceso de compilación de Astro.
-¡Sigue la [Guía de Assets (experimental)](/es/guides/assets/) para empezar a usar la nueva solución de imágenes de Astro hoy mismo!
+```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/"
+# Mi página Markdown
-**`astro:assets` no es un reemplazo completo de `@astrojs/image` en este momento, pero está en desarrollo activo.**
-:::
+
+
+
+
+
+```
+
+Si necesitas más control sobre los atributos de tu imagen, te recomendamos usar el formato de archivo `.mdx`, que te permite incluir el componente `` de Astro o una etiqueta JSX `` además de la sintaxis Markdown. Utiliza la [integración de MDX](/es/guides/integrations-guide/mdx/) para agregar soporte para MDX a Astro.
+
+### Elimina `@astrojs/image`
+
+Si estabas utilizando la integración de imágenes en Astro v2.x, completa los siguientes pasos:
+
+1. Elimina la integración `@astrojs/image`.
+
+ Debes [eliminar la integración](/es/guides/integrations-guide/#eliminando-una-integración) desinstalándola y luego eliminándola de tu archivo `astro.config.mjs`.
+
+ ```js del={3,7}
+ // astro.config.mjs
+ import { defineConfig } from 'astro/config';
+ import image from '@astrojs/image';
+
+ export default defineConfig({
+ integrations: [
+ image(),
+ ]
+ })
+ ```
+
+2. Migra cualquier componente `` existente.
+
+ Cambia todas las declaraciones de `import` de `@astrojs/image/components` a `astro:assets` para poder usar el nuevo componente integrado ``.
+
+ Elimina cualquier atributo del componente que no sean [propiedades de assets de imagen actualmente admitidas](/es/guides/images/#propiedades).
+
+ Por ejemplo, `aspectRatio` ya no es compatible, ya que ahora se infiere automáticamente a partir de los atributos `width` y `height`.
+
+ ```astro title="src/components/MyComponent.astro" del= {2,11} ins={3}
+ ---
+ import { Image } from '@astrojs/image/components';
+ import { Image } from 'astro:assets'
+ import localImage from "../assets/logo.png";
+ const localAlt = "El logo de Astro";
+ ---
+
+
+ ```
+
+3. Elimina cualquier componente `` existente.
-Para encontrar la documentación de como usar `@astrojs/image` en Astro v2, por favor ve a la [documentación del paquete `@astrojs/image`](https://github.com/withastro/astro/blob/main/packages/integrations/image/README.md)
+ Actualmente, la función de assets integrada no incluye un componente ``.
-## Usar imágenes de un CMS o una CDN
+ En su lugar, puedes utilizar los atributos de imagen HTML `srcset` y `sizes`, o la etiqueta `` [para dirección de arte o para crear imágenes responsivas](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction).
-Las CDNs de imágenes funcionan con Astro. Utiliza la URL completa de una imagen como atributo `src` en una etiqueta `` o notación de Markdown.
+4. Elige un servicio de imágenes predeterminado.
-Alternativamente, si la CDN proporciona un SDK para Node.js, puedes usarlo en tu proyecto. Por ejemplo, el [SDK de Cloudinary](https://cloudinary.com/documentation/node_integration) puede generar la etiqueta `` con el `src` apropiado para ti.
+ [Sharp](https://github.com/lovell/sharp) es ahora el servicio de imágenes predeterminado utilizado para `astro:assets`. Si deseas utilizar Sharp, no se requiere ninguna configuración.
-## Alt Text
+ Si prefieres utilizar [Squoosh](https://github.com/GoogleChromeLabs/squoosh) para transformar tus imágenes, actualiza tu configuración con la siguiente opción `image.service`:
-No todos los usuarios pueden ver imágenes de la misma forma, así que la accesibilidad es una preocupación especialmente importante cuando se utilizan imágenes. Usa el atributo `alt` para proveer [texto alt descriptivo](https://www.w3.org/WAI/tutorials/images/) para las imágenes.
+ ```js title="astro.config.mjs" ins={4-6}
+ import { defineConfig, squooshImageService } from 'astro/config';
-Este atributo es requerido para los componentes de integración de imagen `` y ``. Estos componentes arrojarán un error si no se provee un texto alt.
+ export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+ });
+ ```
-Si la imagen es meramente decorativa (p. ej. no contribuye al entendimiento de la página), establece `alt=""` para que la imagen sea entendida adecuadamente e ignorada por los lectores de pantalla.
+### Actualiza los esquemas de Colecciones de Contenido
-## Integraciones de la comunidad
+Ahora puedes declarar una imagen asociada para una entrada de colecciones de contenido, como la imagen de portada de una entrada de blog, en tu metadatos usando su ruta relativa a la carpeta actual.
-Además de la integración oficial [`@astrojs/image`](/es/guides/integrations-guide/image/), existen varias [integraciones de imágenes de la comunidad](https://astro.build/integrations?search=images) para optimizar y trabajar con imágenes en tu proyecto.
+El nuevo helper `image` para colecciones de contenido te permite validar los metadatos de la imagen utilizando Zod. Aprende más sobre [cómo usar imágenes en colecciones de contenido](/es/guides/images/#imágenes-en-colecciones-de-contenido)
\ No newline at end of file
diff --git a/src/content/docs/es/guides/integrations-guide.mdx b/src/content/docs/es/guides/integrations-guide.mdx
index 782258f6b9943..4e038b683ce87 100644
--- a/src/content/docs/es/guides/integrations-guide.mdx
+++ b/src/content/docs/es/guides/integrations-guide.mdx
@@ -126,17 +126,17 @@ Para eliminar una integración, primero desinstala la integración de tu proyect
```shell
- npm uninstall @astrojs/image
+ npm uninstall @astrojs/react
```
```shell
- pnpm uninstall @astrojs/image
+ pnpm uninstall @astrojs/react
```
```shell
- yarn remove @astrojs/image
+ yarn remove @astrojs/react
```
@@ -145,10 +145,11 @@ Después, elimina la integración de tu archivo `astro.config.*`:
```js title="astro.config.mjs" del={3,7}
import { defineConfig } from 'astro/config'
-import image from "@astrojs/image";
+import react from "@astrojs/react";
+
export default defineConfig({
integrations: [
- image()
+ react()
]
})
```
diff --git a/src/content/docs/es/guides/integrations-guide/cloudflare.mdx b/src/content/docs/es/guides/integrations-guide/cloudflare.mdx
index 2947c9709cb8e..e2926b3f941f6 100644
--- a/src/content/docs/es/guides/integrations-guide/cloudflare.mdx
+++ b/src/content/docs/es/guides/integrations-guide/cloudflare.mdx
@@ -54,24 +54,37 @@ export default defineConfig({
Por defecto `"advanced"`
-Cloudflare Pages tiene 2 modos diferentes para implementar funciones, el modo `advanced` que busca el archivo `_worker.js` en `dist`, o un modo `directory` donde las páginas compilarán el worker a partir de una carpeta de funciones en la raíz del proyecto.
+Cloudflare Pages tiene 2 modos diferentes para implementar funciones, el modo `advanced` que busca el archivo `_worker.js` en `dist`, o un modo `directory` donde las páginas compilarán el worker a partir de una carpeta de funciones en la raíz del proyecto. Para la mayoría de los proyectos, el valor predeterminado del adaptador `advanced` será suficiente; la carpeta `dist` contendrá tu proyecto compilado.
-Para la mayoría de los proyectos, la configuración predeterminada del adaptador de `advanced` será suficiente; la carpeta `dist` contendrá tu proyecto compilado. Cambiar al modo de directorio te permite usar [plugins de páginas](https://developers.cloudflare.com/pages/platform/functions/plugins/) como [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) o escribir código personalizado para habilitar el registro de actividades.
+#### `mode:directory`
-En modo directorio, el adaptador compilará la parte del lado del cliente de tu aplicación de la misma manera de forma predeterminada, pero mueve el script del worker a una carpeta `functions` en la raíz del proyecto. En este caso, el adaptador solo colocará un archivo `[[path]].js` en esa carpeta, lo que te permite agregar plugins adicionales y middleware de páginas que se pueden verificar en el control de versiones.
-
-Con la configuración de compilación `split: true`, el adaptador compila un paquete separado para cada página. Esta opción requiere un mantenimiento manual de la carpeta `functions`. Los archivos emitidos por Astro sobrescribirán los archivos `functions` existentes con nombres idénticos, por lo que debes elegir nombres de archivo únicos para cada archivo que agregues manualmente. Además, el adaptador nunca vaciará la carpeta `functions` de archivos obsoletos, por lo que debes limpiar la carpeta manualmente cuando elimines páginas.
-
-Toma en cuenta que el adaptador no admite el uso de [Cloudflare Pages Middleware](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro empaquetará el [middleware de Astro](/es/guides/middleware/) en cada página.
+Cambiar al modo de directorio te permite usar [plugins de páginas](https://developers.cloudflare.com/pages/platform/functions/plugins/) como [Sentry](https://developers.cloudflare.com/pages/platform/functions/plugins/sentry/) o escribir código personalizado para habilitar el registro.
```ts
-// modo directorio.
+// astro.config.mjs
export default defineConfig({
adapter: cloudflare({ mode: 'directory' }),
});
+```
+
+En el modo `directory`, el adaptador compilará la parte del lado del cliente de tu aplicación de la misma manera que en el modo `advanced` de forma predeterminada, pero moverá el script del worker a una carpeta `functions` en la raíz del proyecto. En este caso, el adaptador solo colocará un archivo `[[path]].js` en esa carpeta, lo que te permitirá agregar plugins adicionales y middleware de páginas que pueden ser incluidos en el control de versiones.
+Para en cambio compilar un paquete separado para cada página, establece la opción `functionPerPath` en la configuración de tu adaptador de Cloudflare. Esta opción requiere cierto mantenimiento manual de la carpeta `functions`. Los archivos emitidos por Astro sobrescribirán los archivos `functions` existentes con nombres idénticos, por lo que debes elegir nombres de archivo únicos para cada archivo que agregues manualmente. Además, el adaptador nunca vaciará la carpeta `functions` de archivos obsoletos, por lo que debes limpiar la carpeta manualmente cuando elimines páginas.
+
+```diff
+import {defineConfig} from "astro/config";
+import cloudflare from '@astrojs/cloudflare';
+
+export default defineConfig({
+ adapter: cloudflare({
+ mode: 'directory',
++ functionPerRoute: true
+ })
+})
```
+Ten en cuenta que este adaptador no admite el uso de [Middleware de Cloudflare Pages](https://developers.cloudflare.com/pages/platform/functions/middleware/). Astro incluirá el [middleware de Astro](/es/guides/middleware/) en cada página.
+
## Habilitando la Vista Previa
Para que la vista previa funcione, debes instalar `wrangler`
@@ -146,7 +159,7 @@ Mira la documentación de Cloudflare para [trabajar con variables de entorno](ht
```js
// pages/[id].json.js
-export function get({ params }) {
+export function GET({ params }) {
// Accede a las variables de entorno por solicitud dentro de una función.
const serverUrl = import.meta.env.SERVER_URL;
const result = await fetch(serverUrl + "/user/" + params.id);
diff --git a/src/content/docs/es/guides/integrations-guide/image.mdx b/src/content/docs/es/guides/integrations-guide/image.mdx
deleted file mode 100644
index cd998f6f73cb5..0000000000000
--- a/src/content/docs/es/guides/integrations-guide/image.mdx
+++ /dev/null
@@ -1,722 +0,0 @@
----
-type: integration
-title: '@astrojs/image'
-description: Aprende como usar la integración @astrojs/image en tu proyecto de Astro.
-githubURL: 'https://github.com/withastro/astro/tree/main/packages/integrations/image/'
-hasREADME: true
-category: other
-i18nReady: true
----
-
-import Video from '~/components/Video.astro';
-
-> ⚠️ ¡Esta integración será archivada en Astro v3.0 (Otoño 2023) en favor del módulo `astro:assets`. Por favor, consulta la [documentación de Assets](/es/guides/assets/) para más información!
-
-Esta **[integración de Astro][astro-integration]** optimiza las imágenes en tu [proyecto de Astro](https://astro.build/). Es compatible con Astro v2 solo para todos los sitios estáticos y para [algunos hosts de implementación de renderizado en el lado del servidor](#instalación).
-
-## ¿Por qué `@astrojs/image`?
-
-Las imágenes juegan un papel importante en el rendimiento general y la usabilidad del sitio. Servir imágenes con el tamaño adecuado marca la diferencia, pero a menudo es complicado automatizar este proceso.
-
-Esta integración proporciona los componentes `` y ``, así como un transformador de imágenes básico, con soporte completo para sitios estáticos y renderizado en el lado del servidor. El transformador de imágenes incorporado también es reemplazable, abriendo la puerta a futuras integraciones que funcionen con tu servicio de imágenes alojado favorito.
-
-## Instalación
-
-Junto con nuestra integración, recomendamos instalar [sharp](https://sharp.pixelplumbing.com/) cuando sea apropiado.
-
-El transformador de imágenes predeterminado de `@astrojs/image` está basado en [Squoosh](https://github.com/GoogleChromeLabs/squoosh) y utiliza bibliotecas de WebAssembly para admitir la mayoría de los entornos de implementación, incluidos aquellos que no admiten sharp, como StackBlitz.
-
-Para obtener compilaciones más rápidas y un control más preciso de las transformaciones de imagen, instala sharp además de `@astrojs/image` si
-
-* Estás construyendo un sitio estático con Astro.
-* Estás utilizando un host de despliegue SSR compatible con NodeJS mediante `@astrojs/netlify/functions`, `@astrojs/vercel/serverless` o `@astrojs/node`.
-
-Ten en cuenta que `@astrojs/image` no es compatible actualmente con
-
-* Cloudflare SSR
-* `@astrojs/deno`
-* `@astrojs/netlify/edge-functions`
-* `@astrojs/vercel/edge`
-
-### Instalación rapida
-
-La herramienta de línea de comandos `astro add` automatiza la instalación por ti. Ejecuta uno de los siguientes comandos en una nueva ventana de terminal. (Si no estás seguro de qué gestor de paquetes estás usando, ejecuta el primer comando.) Luego, sigue las instrucciones y escribe "y" en la terminal (es decir, "sí") para cada uno.
-
-```sh
-# Usando NPM
-npx astro add image
-# Usando Yarn
-yarn astro add image
-# Usando PNPM
-pnpm astro add image
-```
-
-Si tienes algún problema, [no dudes en informarnos en GitHub](https://github.com/withastro/astro/issues) y prueba los pasos de instalación manual a continuación.
-
-### Instalación manual
-
-Primero, instala el paquete `@astrojs/image` utilizando tu gestor de paquetes. Si estás utilizando npm o no estás seguro, ejecuta lo siguiente en tu terminal:
-
-```sh
-npm install @astrojs/image
-```
-
-Luego, aplica esta integración a tu archivo `astro.config.*` utilizando la propiedad `integrations`:
-
-```js ins={3} "image()"
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- // ...
- integrations: [image()],
-});
-```
-
-### Instalando `sharp` (opcional)
-
-Primero, instala el paquete `sharp` utilizando tu administrador de paquetes. Si estás utilizando npm o no estás seguro, ejecuta lo siguiente en la terminal:
-
-```sh
-npm install sharp
-```
-
-A continuación, actualiza la integración en tu archivo `astro.config.*` para utilizar el transformador de imágenes integrado `sharp`.
-
-```js ins={8}
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- // ...
- integrations: [
- image({
- serviceEntryPoint: '@astrojs/image/sharp',
- }),
- ],
-});
-```
-
-### Actualiza `env.d.ts`
-
-Para tener la mejor experiencia de desarrollo, agrega las definiciones de tipos de las integraciones a tu archivo `env.d.ts` del proyecto.
-
-```typescript
-// Reemplaza `astro/client` con `@astrojs/image/client`
-///
-```
-
-O, alternativamente, si tu proyecto está utilizando los tipos a través de un archivo `tsconfig.json`
-
-```json
-{
- "compilerOptions": {
- // Reemplaza `astro/client` con `@astrojs/image/client`
- "types": ["@astrojs/image/client"]
- }
-}
-```
-
-## Uso
-
-```astro title="src/pages/index.astro"
----
-import { Image, Picture } from '@astrojs/image/components';
-import heroImage from '../assets/hero.png';
----
-// imagen optimizada, manteniendo el ancho, alto y formato de imagen originales
-
-// especifica varios tamaños para imágenes responsivas o dirección de arte
-
-```
-
-Los transformadores de imagen incluidos admiten el redimensionamiento de imágenes y la codificación en diferentes formatos de imagen. Los servicios de imágenes de terceros también podrán agregar soporte para transformaciones personalizadas (p. ej: `blur`, `filter`, `rotate`, etc).
-
-Los componentes `` y `` de Astro requieren el atributo `alt`, que proporciona texto descriptivo para las imágenes. Se mostrará un aviso si falta el texto alternativo, y en futuras versiones de la integración se generará un error si no se proporciona texto alternativo.
-
-Si la imagen es simplemente decorativa (es decir, no contribuye a la comprensión de la página), establece `alt=""` para que la imagen sea correctamente entendida y omitida por los lectores de pantalla.
-
-### ``
-
-El componente integrado `` se utiliza para crear una etiqueta `` optimizada tanto para imágenes remotas accedidas por URL como para imágenes locales importadas desde el directorio `src/` de tu proyecto.
-
-Además de las propiedades específicas del componente, cualquier atributo HTML válido para la etiqueta`` incluido en el componente `` se incluirá en la etiqueta `` generada.
-
-#### src
-
-
-
-Fuente del archivo de imagen original.
-
-Para imágenes remotas, proporciona la URL completa. (p. ej. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`)
-
-Para imágenes ubicadas en el directorio `src/` de tu proyecto, utiliza la ruta del archivo relativa al directorio `src/`. (p. ej. `src="../assets/source-pic.png"`)
-
-Para imágenes ubicadas en el directorio `public/`, utiliza la ruta URL relativa al directorio `public/`. (p. ej. `src="/images/public-image.jpg"`). Estas funcionan como imágenes remotas.
-
-#### alt
-
-
-
-Define una descripción alternativa de texto de la imagen.
-
-Establécelo como un string vacio (`alt=""`) si la imagen no es una parte clave del contenido (p. ej, si es una decoración o un píxel de seguimiento).
-
-#### format
-
-
-
-El formato de salida que se utilizará en la imagen optimizada. Se utilizará el formato de la imagen original si no se proporciona el valor `format`.
-
-Esta propiedad es obligatoria para imágenes remotas cuando se utiliza el transformador de imágenes predeterminado Squoosh, esto se debe a que no se puede inferir el formato original.
-
-A partir de la versión 0.15.0, puedes utilizar el componente `` cuando trabajas con imágenes SVG, pero la opción `svg` solo se puede utilizar cuando la imagen original es un archivo `.svg`. Otros formatos de imagen (como `.png` o `.jpg`) cannot be converted into vector images. La imagen `.svg` en sí no será transformada, pero la etiqueta `` final será optimizada correctamente por la integración.
-
-#### quality
-
-
-
-La calidad de compresión utilizada durante la optimización. El servicio de imágenes utilizará su propia calidad por defecto dependiendo del formato de la imagen si no se proporciona.
-
-#### width
-
-
-
-La altura deseada de la imagen de salida. Combínalo con `width` para recortar la imagen a un tamaño exacto, o con `aspectRatio` para calcular y recortar automáticamente el ancho.
-
-Las dimensiones son opcionales para las imágenes locales. Si no se proporcionan, se utilizará el tamaño original de la imagen.
-
-Para las imágenes remotas, incluyendo las imágenes en la carpeta `public/`, la integración necesita poder calcular las dimensiones de la imagen optimizada. Esto se puede hacer proporcionando `width` y `height` o proporcionando una dimensión y un `aspectRatio`.
-
-#### height
-
-
-
-La altura deseada de la imagen de salida. Combínalo con `width` para recortar la imagen a un tamaño exacto, o con `aspectRatio` para calcular y recortar automáticamente el ancho.
-
-Las dimensiones son opcionales para las imágenes locales. Si no se proporcionan, se utilizará el tamaño original de la imagen.
-
-Para las imágenes remotas, incluyendo las imágenes en la carpeta `public/`, la integración necesita poder calcular las dimensiones de la imagen optimizada. Esto se puede hacer proporcionando `width` y `height` o proporcionando una dimensión y un `aspectRatio`.
-
-#### aspectRatio
-
-
-
-La relación de aspecto deseada de la imagen de salida. Se combina con `width` o `height` para calcular automáticamente y recortar la otra dimensión.
-
-Se puede proporcionar un `string` en la forma de `{width}:{height}`, por ejemplo: `16:9` o `3:4`.
-
-También se puede proporcionar un `number`, lo cual es útil cuando el aspect ratio se calcula en tiempo de generación. Esto puede ser un número en línea como `1.777` o en línea como una expresión JSX como `aspectRatio={16/9}`.
-
-Para imágenes remotas, incluidas las imágenes en la carpeta `public/`, la integración necesita poder calcular las dimensiones de la imagen optimizada. Esto se puede hacer proporcionando `width` y `height` o proporcionando una dimensión y un `aspectRatio`.
-
-#### background
-
-
-
-> Esto no es compatible con el servicio Squoosh por defecto. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo usar el servicio `sharp` en su lugar.
-
-El color de fondo se utiliza para rellenar el fondo restante cuando se utiliza contain para la propiedad `fit`.
-
-El color de fondo a utilizar para reemplazar el canal alfa con el método `flatten` de `sharp`. En caso de que el formato de salida no admita transparencia (p. ej. `jpeg`), se recomienda incluir un color de fondo; de lo contrario, se utilizará el negro como reemplazo predeterminado para los píxeles transparentes.
-
-El parámetro acepta un valor de tipo `string`.
-
-El parámetro puede ser un [color HTML con nombre](https://www.w3schools.com/tags/ref_colornames.asp), una representación hexadecimal del color con 3 o 6 caracteres hexadecimales en el formato `#123[abc]`, o una definición RGB en el formato `rgb(100,100,100)`, o una definición RGBA en el formato `rgba(100,100,100, 0.5)`.
-
-#### fit
-
-
-
-> Esto no está soportado por el servicio predeterminado de Squoosh. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo utilizar el servicio `sharp` en su lugar. Lee más sobre [cómo redimensionar imágenes con `sharp`](https://sharp.pixelplumbing.com/api-resize).
-
-Cómo debe redimensionarse la imagen para que se ajuste tanto el `height` como el `width`.
-
-#### position
-
-
-
-> Esto no está soportado por el servicio predeterminado de Squoosh. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo utilizar el servicio `sharp` en su lugar. Lee más sobre [cómo redimensionar imágenes con `sharp`](https://sharp.pixelplumbing.com/api-resize).
-
-La posición del recorte cuando el ajuste fit es `cover` o `contain`.
-
-### ``
-
-El componente integrado `` se utiliza para crear un elemento `` optimizado tanto para imágenes remotas accedidas por URL como para imágenes locales importadas desde el directorio `src/` de tu proyecto.
-
-Además de las propiedades específicas del componente, cualquier atributo HTML válido para el elemento `` incluido en el componente `` será incluido en el elemento `` construido.
-
-#### src
-
-
-
-Fuente del archivo de imagen original.
-
-Para imágenes remotas, proporciona la URL completa. (p. ej. `src="https://astro.build/assets/blog/astro-1-release-update.avif"`)
-
-Para imágenes ubicadas en el directorio `src/` de tu proyecto: utiliza la ruta del archivo relativa al directorio `src/`. (p. ej. `src="../assets/source-pic.png"`)
-
-Para imágenes ubicadas en el directorio `public/` de tu proyecto: utiliza la ruta de URL relativa al directorio `public/`. (p. ej. `src="/images/public-image.jpg"`). Estas funcionan como imágenes remotas.
-
-#### alt
-
-
-
-Define una descripción de texto alternativa de la imagen.
-
-Establécelo como una cadena vacía (`alt=""`) si la imagen no es una parte clave del contenido (p. ej, si es una decoración o un píxel de seguimiento).
-
-#### sizes
-
-
-
-La propiedad `sizes` del objeto HTMLImageElement te permite especificar el ancho de diseño de la imagen para cada una de las condiciones de los medios en una lista.
-
-Consulta [MDN](https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/sizes) para más detalles.
-
-#### widths
-
-
-
-La lista de tamaños que se deben generar para las imágenes responsivas. Esto se combina con `aspectRatio` para calcular las dimensiones finales de cada imagen generada.
-
-```astro
-// Genera tres imágenes: una de 400x400, otra de 800x800, y otra de 1200x1200
-
-```
-
-#### aspectRatio
-
-
-
-La relación de aspecto deseada de la imagen de salida. Esto se combina con los `widths` para calcular las dimensiones finales de cada imagen generada.
-
-Se puede proporcionar un `string` en la forma de `{width}:{height}`, por ejemplo: `16:9` o `3:4`.
-
-También se puede proporcionar un `number`, lo cual es útil cuando el aspect ratio se calcula en tiempo de generación. Esto puede ser un número en línea como `1.777` o en línea como una expresión JSX como `aspectRatio={16/9}`.
-
-Para imágenes remotas, incluyendo imágenes en `public/`, se requiere `aspectRatio` para asegurar que el `height` es correcto se pueda calcular durante la generación.
-
-#### formats
-
-
-
-Los formatos de salida que se utilizarán en la imagen optimizada. Si no se proporciona ninguno, se utilizarán `webp` y `avif` además del formato de imagen original.
-
-Para imágenes remotas, incluidas las imágenes en `public/`, el formato de imagen original es desconocido. Si no se proporciona, se utilizarán solo `webp` y `avif`.
-
-#### background
-
-
-
-> Esto no es compatible con el servicio Squoosh por defecto. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo usar el servicio `sharp` en su lugar.
-
-El color de fondo a utilizar para reemplazar el canal alfa con el método `flatten` de `sharp`. En caso de que el formato de salida no admita transparencia (p. ej. `jpeg`), se recomienda incluir un color de fondo; de lo contrario, se utilizará el negro como reemplazo predeterminado para los píxeles transparentes.
-
-El parámetro acepta un valor de tipo `string`.
-
-El parámetro puede ser un [color HTML con nombre](https://www.w3schools.com/tags/ref_colornames.asp), una representación hexadecimal del color con 3 o 6 caracteres hexadecimales en el formato `#123[abc]`, o una definición RGB en el formato `rgb(100,100,100)`.
-
-#### fit
-
-
-
-> Esto no está soportado por el servicio predeterminado de Squoosh. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo utilizar el servicio `sharp` en su lugar. Lee más sobre [cómo redimensionar imágenes con `sharp`](https://sharp.pixelplumbing.com/api-resize).
-
-Cómo la imagen debe ser redimensionada para el `height` y el `width`.
-
-#### position
-
-
-
-> Esto no está soportado por el servicio predeterminado de Squoosh. Consulta la [sección de instalación](#instalando-sharp-opcional) para obtener más detalles sobre cómo utilizar el servicio `sharp` en su lugar. Lee más sobre [cómo redimensionar imágenes con `sharp`](https://sharp.pixelplumbing.com/api-resize).
-
-La posición del recorte cuando el ajuste fit es `cover` o `contain`.
-
-### `getImage`
-
-Esta es la función auxiliar utilizada por el componente `` para construir los atributos `` para la imagen transformada. Esta función auxiliar se puede utilizar directamente para casos de uso más complejos que no son compatibles actualmente con el componente ``.
-
-Esta función auxiliar recibe un objeto con las mismas propiedades que el componente `` y devuelve un objeto con los atributos que deben incluirse en el elemento final ``.
-
-Esto puede ser útil si necesitas agregar enlaces de precarga a la etiqueta `` de una página.
-
-```astro
----
-import { getImage } from '@astrojs/image';
-
-const { src } = await getImage({
- src: import('../assets/hero.png'),
- alt: 'My hero image',
-});
----
-
-
-
-
-
-
-```
-
-### `getPicture`
-
-Esta es la función auxiliar utilizada por el componente `` para construir múltiples tamaños y formatos para imágenes responsivas. Esta función auxiliar se puede utilizar directamente para casos de uso más complejos que no son compatibles actualmente con el componente ``.
-
-Esta función auxiliar recibe un objeto con las mismas propiedades que el componente `` y devuelve un objeto con los atributos que deben incluirse en el elemento final `` **y** auna lista de fuentes que deben utilizarse para renderizar todos los elementos `` para el elemento ``.
-
-## Configuración
-
-La integración se puede configurar para ejecutarse con un servicio de imágenes diferente, ya sea un servicio de imágenes alojado o un transformador de imágenes completo que se ejecuta localmente en tu compilación o implementación de SSR.
-
-> Durante el desarrollo, es posible que las imágenes locales aún no se hayan publicado y no estén disponibles para los servicios de imágenes alojados. Las imágenes locales siempre utilizarán el servicio de imágenes incorporado al usar `astro dev`.
-
-### config.serviceEntryPoint
-
-El `serviceEntryPoint` debe resolver al servicio de imágenes instalado desde NPM. El punto de entrada predeterminado es `@astrojs/image/squoosh`,que resuelve al punto de entrada exportado desde el `package.json` de esta integración.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [
- image({
- // Ejemplo: El punto de entrada para un servicio de imágenes de terceros instalado desde NPM
- serviceEntryPoint: 'my-image-service/astro.js',
- }),
- ],
-});
-```
-
-### config.logLevel
-
-El control `logLevel` se puede utilizar para controlar la cantidad de detalles que registra la integración durante las compilaciones. Esto puede ser útil para rastrear una imagen o transformación específica que está tardando mucho tiempo en construirse.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [image({
- // niveles admitidos: 'debug' | 'info' | 'warn' | 'error' | 'silent'
- // por defecto: 'info'
- logLevel: 'debug',
- }),
- ],
-});
-```
-
-### config.cacheDir
-
-Durante las compilaciones estáticas, la integración almacenará en caché las imágenes transformadas para evitar reconstruir la misma imagen en cada compilación. Esto puede ser especialmente útil si estás utilizando un servicio de alojamiento que te permite almacenar en caché los activos de compilación para implementaciones futuras.
-
-Las imágenes locales se almacenarán en caché durante 1 año y se invalidarán cuando se modifique el archivo de imagen original. Las imágenes remotas se almacenarán en caché en función de las cabeceras de caché de la respuesta de `fetch()`, de manera similar a cómo un CDN administraría la caché.
-
-De forma predeterminada, las imágenes transformadas se almacenarán en caché en `./node_modules/.astro/image`. Esto se puede configurar en las opciones de configuración de la integración.
-
-```js
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import image from '@astrojs/image';
-
-export default defineConfig({
- integrations: [
- image({
- // puede ser útil si tu proveedor de alojamiento permite el almacenamiento en caché entre las compilaciones de CI.
- cacheDir: "./.cache/image",
- }),
- ],
-});
-```
-
-El almacenamiento en caché también se puede desactivar utilizando `cacheDir: false`.
-
-## Ejemplos
-
-### Imágenes locales
-
-Los archivos de imagen en el directorio `src/` de tu proyecto se pueden importar en el frontmatter y pasarse directamente al componente `` como el valor del atributo `src=`. También se requiere el atributo `alt`.
-
-Todas las demás propiedades son opcionales y se establecerán en los valores predeterminados del archivo de imagen original si no se proporcionan.
-
-```astro
----
-import { Image } from '@astrojs/image/components';
-import heroImage from '../assets/hero.png';
----
-
-// imagen optimizada, manteniendo el ancho, alto y formato original
-
-
-// la altura se recalculará para que coincida con la relación de aspecto original
-
-
-// recortando a un ancho y alto específicos
-
-
-// recortando a una relación de aspecto específica y convirtiendo a formato avif
-
-
-// las importaciones de imágenes también se pueden incluir directamente en línea
-
-```
-
-#### Imágenes en `/public`
-
-El componente `` también se puede utilizar con imágenes almacenadas en el directorio `public/` y el atributo `src=` es relativo a la carpeta public. Se tratará como una imagen remota, lo cual requiere proporcionar tanto `width` y `height`, o una dimensión y un atributo `aspectRatio`.
-
-Tu imagen original se copiará sin procesar a la carpeta de compilación, al igual que todos los archivos ubicados en public/, y la integración de imágenes de Astro también devolverá versiones optimizadas de la imagen.
-
-Por ejemplo, utiliza una imagen ubicada en `public/social.png` en construcciones estáticas o de SSR de la siguiente manera:
-
-```astro title="src/pages/page.astro"
----
-import { Image } from '@astrojs/image/components';
-import socialImage from '/social.png';
----
-
-// En construcciones estáticas: la imagen se compilará y optimizará en `/dist`. // En construcciones de SSR: el servidor optimizará la imagen cuando sea solicitada por un navegador.
-
-```
-
-### Imágenes remotas
-
-Las imágenes remotas se pueden transformar con el componente `` component. El componente `` necesita conocer las dimensiones finales para el elemento `` para evitar cambios en el diseño del contenido. Para imágenes remotas, esto significa que debes proporcionar `width` y `height`, o una de las dimensiones más el `aspectRatio` requerido.
-
-```astro
----
-import { Image } from '@astrojs/image/components';
-
-const imageUrl = 'https://astro.build/assets/press/full-logo-dark.png';
----
-
-// Recortando a un ancho y alto específicos
-
-
-// La altura se recalculará para que coincida con el aspect ratio
-
-```
-
-### Imágenes responsivas
-
-El componente `` se puede utilizar para construir automáticamente un elemento `` con múltiples tamaños y formatos. Consulta [MDN](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction) para obtener más información sobre imágenes responsivas y dirección de arte.
-
-Por defecto, la imagen incluirá formatos para `avif` y `webp`. Solo para imágenes locales, también se incluirá el formato original de la imagen.
-
-Para imágenes remotas, se requiere un `aspectRatio` para asegurar que se pueda calcular la `altura` correcta en el momento de la construcción.
-
-```astro
----
-import { Picture } from '@astrojs/image/components';
-import hero from '../assets/hero.png';
-
-const imageUrl =
- 'https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png';
----
-
-// Imagen local con múltiples tamaños
-
-
-// Imagen remota (se requiere aspect ratio)
-
-
-// Las importaciones en línea son compatibles.
-
-```
-
-### Estableciendo valores predeterminados
-
-Por el momento, no hay forma de especificar valores predeterminados para todos los componentes `` y ``. Los atributos requeridos deben establecerse en cada componente individual.
-
-Como una alternativa, puedes envolver estos componentes en otro componente de Astro para reutilizarlos. Por ejemplo, podrías crear un componente para las imágenes de tu blog:
-
-```astro title="src/components/BlogPostImage.astro"
----
-import { Picture } from '@astrojs/image/components';
-const { src, ...attrs } = Astro.props;
----
-
-
-```
-
-### Usando `` con la integración de imágenes
-
-La integración oficial de imágenes cambiará las importaciones de imágenes para devolver un objeto en lugar de un string de origen.
-
-El objeto tiene las siguientes propiedades, derivadas del archivo importado:
-
-```ts
-{
- src: string;
- width: number;
- height: number;
- format: 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp';
-}
-```
-
-Si tienes instalada la integración de imágenes, consulta la propiedad `src` del objeto al usar ``.
-
-```astro ".src"
----
-import rocket from '../images/rocket.svg';
----
-
-```
-
-Alternativamente, agrega `?url` a tus importaciones para decirles que devuelvan un string de origen.
-
-```astro "?url"
----
-import rocket from '../images/rocket.svg?url';
----
-
-```
-
-## Solución de problemas
-
-* Si tu instalación no parece funcionar, intenta reiniciar el servidor de desarrollo.
-* Si editas y guardas un archivo pero no ves que tu sitio se actualice en consecuencia, intenta refrescar la página.
-* Si refrescar la página no actualiza tu vista previa, o si una nueva instalación no parece estar funcionando, entonces reinicia el servidor de desarrollo.
-
-Para obtener ayuda, revisa el canal `#support` en [Discord](https://astro.build/chat). ¡Nuestros amigables miembros del Escuadrón de Soporte están aquí para ayudarte!
-
-Puedes revisar nuestra [Documentación de Integración de Astro][astro-integration] para más información sobre integraciones.
-
-[astro-integration]: /es/guides/integrations-guide/
-
-## Contribuyendo
-
-Este paquete es mantenido por el equipo central de Astro. ¡Estás invitado a enviar un problema o PR!
-
-## Changelog
-
-Consulta el [CHANGELOG.md](https://github.com/withastro/astro/tree/main/packages/integrations/image/CHANGELOG.md) para un historial de cambios en esta integración.
diff --git a/src/content/docs/es/guides/integrations-guide/mdx.mdx b/src/content/docs/es/guides/integrations-guide/mdx.mdx
index 18b7135fb3265..15d1349fdc1fe 100644
--- a/src/content/docs/es/guides/integrations-guide/mdx.mdx
+++ b/src/content/docs/es/guides/integrations-guide/mdx.mdx
@@ -70,7 +70,7 @@ export default defineConfig({
Con la integración MDX de Astro, puedes [añadir páginas MDX a tu proyecto](/es/guides/markdown-content/#páginas-de-markdown-y-mdx) añadiendo archivos `.mdx` dentro de tu directorio `src/pages/`. También puedes [importar archivos `.mdx`](/es/guides/markdown-content/#importando-markdown) en archivos `.astro`.
-La integración MDX de Astro agrega características adicionales a MDX estándar, incluyendo el frontmatter estilo Markdown. Esto te permite utilizar la mayoría de las características de Markdown incorporadas en Astro, como una [propiedad especial de frontmatter `layout`](/es/guides/markdown-content/#layout-en-el-frontmatter) y una [propiedad para marcar una página como borrador](/es/guides/markdown-content/#páginas-de-borrador).
+La integración MDX de Astro agrega características adicionales a MDX estándar, incluyendo el frontmatter estilo Markdown. Esto te permite utilizar la mayoría de las características de Markdown incorporadas en Astro, como una [propiedad especial de frontmatter `layout`](/es/guides/markdown-content/#layout-en-el-frontmatter).
Consulta cómo funciona MDX en Astro con ejemplos en nuestra [guía de Markdown y MDX](/es/guides/markdown-content/).
diff --git a/src/content/docs/es/guides/integrations-guide/netlify.mdx b/src/content/docs/es/guides/integrations-guide/netlify.mdx
index 1c928b86517bb..10dd258c61937 100644
--- a/src/content/docs/es/guides/integrations-guide/netlify.mdx
+++ b/src/content/docs/es/guides/integrations-guide/netlify.mdx
@@ -59,28 +59,11 @@ Si prefieres instalar el adaptador manualmente, completa los siguientes dos paso
});
```
-### Funciones Edge
-
-Netlify tiene dos plataformas serverless, [Funciones Netlify](https://docs.netlify.com/functions/overview/) y [Funciones Edge de Netlify](https://docs.netlify.com/edge-functions/overview/). Con Funciones Edge tu código se distribuye más cerca de tus usuarios, reduciendo la latencia.
-
-Para desplegar con Funciones Edge, usa `netlify/edge-functions` en el archivo de configuración de Astro en lugar de `netlify/functions`.
-
-```js ins={3}
-// astro.config.mjs
-import { defineConfig } from 'astro/config';
-import netlify from '@astrojs/netlify/edge-functions';
-
-export default defineConfig({
- output: 'server',
- adapter: netlify(),
-});
-```
-
### Ejecutar middleware en Funciones Edge
Al desplegar en Netlify Functions, puedes elegir utilizar una Función Edge para ejecutar tu middleware Astro.
-Para activarlo, establece la opción de configuración de Astro `build.excludeMiddleware` en `true`:
+Para activarlo, establece la opción de configuración `edgeMiddleware` en `true`:
```js ins={9}
// astro.config.mjs
@@ -89,10 +72,9 @@ import netlify from '@astrojs/netlify/functions';
export default defineConfig({
output: 'server',
- adapter: netlify(),
- build: {
- excludeMiddleware: true,
- },
+ adapter: netlify({
+ edgeMiddleware: true,
+ }),
});
```
@@ -138,10 +120,9 @@ import netlify from '@astrojs/netlify/functions';
export default defineConfig({
output: 'server',
- adapter: netlify(),
- build: {
- split: true,
- },
+ adapter: netlify({
+ functionPerRoute: true,
+ }),
});
```
@@ -262,7 +243,7 @@ Verificamos los tipos mime comunes para archivos de audio, imagen y video. Para
import fs from 'node:fs';
-export function get() {
+export function GET() {
const buffer = fs.readFileSync('../image.jpg');
// Regresa el buffer directamente, @astrojs/netlify codificará en base64 el cuerpo
diff --git a/src/content/docs/es/guides/integrations-guide/node.mdx b/src/content/docs/es/guides/integrations-guide/node.mdx
index 936b309d1ddd7..3c3bd915963db 100644
--- a/src/content/docs/es/guides/integrations-guide/node.mdx
+++ b/src/content/docs/es/guides/integrations-guide/node.mdx
@@ -162,7 +162,7 @@ Para el modo standalone, el servidor maneja el servidor de archivos además de l
Puedes anular el host y el puerto en los que se ejecuta el servidor independiente pasándolos como variables de entorno en tiempo de ejecución:
```shell
-HOST=0.0.0.0 PORT=3000 node ./dist/server/entry.mjs
+HOST=0.0.0.0 PORT=4321 node ./dist/server/entry.mjs
```
#### HTTPS
diff --git a/src/content/docs/es/guides/integrations-guide/preact.mdx b/src/content/docs/es/guides/integrations-guide/preact.mdx
index 045a415500ea4..d9f96cc3e7aeb 100644
--- a/src/content/docs/es/guides/integrations-guide/preact.mdx
+++ b/src/content/docs/es/guides/integrations-guide/preact.mdx
@@ -117,6 +117,41 @@ Consulta las documentaciónes de [`pnpm` overrides](https://pnpm.io/package_json
Actualmente, la opción `compat` solo funciona para las bibliotecas de React que exportan código como ESM. Si ocurre un error durante la compilación, intenta agregar la biblioteca a `vite.ssr.noExternal: ['the-react-library']` en tu archivo `astro.config.mjs`.
:::
+## Opciones
+
+### Combinando múltiples frameworks JSX
+
+Cuando estás utilizando múltiples frameworks JSX (React, Preact, Solid) en el mismo proyecto, Astro necesita determinar qué transformaciones específicas del framework JSX deben usarse para cada uno de tus componentes. Si solo has agregado una integración de framework JSX a tu proyecto, no se necesita configuración adicional.
+
+Utiliza las opciones de configuración `include` (obligatoria) y `exclude` (opcional) para especificar qué archivos pertenecen a qué framework. Proporciona un array de archivos y/o carpetas en `include` para cada framework que estés utilizando. Puedes utilizar comodines para incluir múltiples rutas de archivo.
+
+Recomendamos colocar los componentes comunes de los frameworks en la misma carpeta (p. ej. `/components/react/` y `/components/solid/`) para facilitar la especificación de tus inclusiones, pero esto no es obligatorio:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Habilita varios frameworks para admitir todo tipo de componentes diferentes.
+ // ¡No se necesita `include` si solo estás utilizando un solo framework JSX!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
## Ejemplos
* El [ejemplo Astro Preact](https://github.com/withastro/astro/tree/latest/examples/framework-preact) muestra cómo utilizar un componente interactivo de Preact en un proyecto de Astro.
diff --git a/src/content/docs/es/guides/integrations-guide/react.mdx b/src/content/docs/es/guides/integrations-guide/react.mdx
index f7d97f4aaa598..c003d00f9e980 100644
--- a/src/content/docs/es/guides/integrations-guide/react.mdx
+++ b/src/content/docs/es/guides/integrations-guide/react.mdx
@@ -75,6 +75,39 @@ Para usar tu primer componente React en Astro, dirígete a nuestra [documentaci
## Opciones
+### Combinando múltiples frameworks JSX
+
+Cuando estás utilizando múltiples frameworks JSX (React, Preact, Solid) en el mismo proyecto, Astro necesita determinar qué transformaciones específicas del framework JSX deben usarse para cada uno de tus componentes. Si solo has agregado una integración de framework JSX a tu proyecto, no se necesita configuración adicional.
+
+Utiliza las opciones de configuración `include` (obligatoria) y `exclude` (opcional) para especificar qué archivos pertenecen a qué framework. Proporciona un array de archivos y/o carpetas en `include` para cada framework que estés utilizando. Puedes utilizar comodines para incluir múltiples rutas de archivo.
+
+Recomendamos colocar los componentes comunes de los frameworks en la misma carpeta (p. ej. `/components/react/` y `/components/solid/`) para facilitar la especificación de tus inclusiones, pero esto no es obligatorio:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Habilita varios frameworks para admitir todo tipo de componentes diferentes.
+ // ¡No se necesita `include` si solo estás utilizando un solo framework JSX!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
### Análisis de los hijos
Los hijos pasados a un componente de React desde un componente de Astro se analizan como strings simples, no como nodos de React.
diff --git a/src/content/docs/es/guides/integrations-guide/solid-js.mdx b/src/content/docs/es/guides/integrations-guide/solid-js.mdx
index 2f7e13c15f865..c7d9eb54e7e28 100644
--- a/src/content/docs/es/guides/integrations-guide/solid-js.mdx
+++ b/src/content/docs/es/guides/integrations-guide/solid-js.mdx
@@ -73,6 +73,41 @@ Para usar tu primer componente con solidjs en Astro, dirígete a nuestra [docume
* 💧 opciones de hidratación del lado del cliente, y
* 🤝 oportunidades para mezclar y anidar frameworks juntos
+## Opciones
+
+### Combinando múltiples frameworks JSX
+
+Cuando estás utilizando múltiples frameworks JSX (React, Preact, Solid) en el mismo proyecto, Astro necesita determinar qué transformaciones específicas del framework JSX deben usarse para cada uno de tus componentes. Si solo has agregado una integración de framework JSX a tu proyecto, no se necesita configuración adicional.
+
+Utiliza las opciones de configuración `include` (obligatoria) y `exclude` (opcional) para especificar qué archivos pertenecen a qué framework. Proporciona un array de archivos y/o carpetas en `include` para cada framework que estés utilizando. Puedes utilizar comodines para incluir múltiples rutas de archivo.
+
+Recomendamos colocar los componentes comunes de los frameworks en la misma carpeta (p. ej. `/components/react/` y `/components/solid/`) para facilitar la especificación de tus inclusiones, pero esto no es obligatorio:
+
+```js
+import { defineConfig } from 'astro/config';
+import preact from '@astrojs/preact';
+import react from '@astrojs/react';
+import svelte from '@astrojs/svelte';
+import vue from '@astrojs/vue';
+import solid from '@astrojs/solid-js';
+
+export default defineConfig({
+ // Habilita varios frameworks para admitir todo tipo de componentes diferentes.
+ // ¡No se necesita `include` si solo estás utilizando un solo framework JSX!
+ integrations: [
+ preact({
+ include: ['**/preact/*'],
+ }),
+ react({
+ include: ['**/react/*'],
+ }),
+ solid({
+ include: ['**/solid/*'],
+ }),
+ ],
+});
+```
+
## Solución de problemas
Para obtener ayuda, consulta el canal de `#support` en [Discord](https://astro.build/chat). ¡Nuestros amables miembros del equipo de soporte están aquí para ayudar!
diff --git a/src/content/docs/es/guides/integrations-guide/vercel.mdx b/src/content/docs/es/guides/integrations-guide/vercel.mdx
index 53e28611188b8..091d3854a786f 100644
--- a/src/content/docs/es/guides/integrations-guide/vercel.mdx
+++ b/src/content/docs/es/guides/integrations-guide/vercel.mdx
@@ -62,19 +62,13 @@ Si prefieres instalar el adaptador manualmente, completa los siguientes dos paso
Puedes desplegar en diferentes objetivos:
-* `edge`: SSR dentro de una [función Edge](https://vercel.com/docs/concepts/functions/edge-functions).
* `serverless`: SSR dentro de una [función Node.js](https://vercel.com/docs/concepts/functions/serverless-functions).
* `static`: genera un sitio estático siguiendo los formatos de salida, redirecciones, etc. de Vercel.
-:::note
-Desplegar en el Edge tiene [sus limitaciones](https://vercel.com/docs/concepts/functions/edge-functions#known-limitations). Una función edge no puede ser más grande de 1 MB y no admite API nativas de Node.js, entre otras.
-:::
-
Puedes cambiar el destino modificando la importación:
```js
-import vercel from '@astrojs/vercel/edge';
import vercel from '@astrojs/vercel/serverless';
import vercel from '@astrojs/vercel/static';
```
@@ -97,7 +91,7 @@ Para configurar este adaptador, pasa un objeto a la invocación de función `ver
### analytics
**Tipo:** `boolean`
-**Disponible para:** Serverless, Edge y Estático
+**Disponible para:** Serverless y Static
**Agregado en:** `@astrojs/vercel@3.1.0`
Puedes habilitar [Vercel Analytics](https://vercel.com/analytics) (incluyendo Web Vitals y Audiences) configurando `analytics: true`. Esto inyectará los scripts de seguimiento de Vercel en todas tus páginas.
@@ -118,7 +112,7 @@ export default defineConfig({
### imagesConfig
**Tipo:** `VercelImageConfig`
-**Disponible para:** Edge, Serverless, Static
+**Disponible para:** Serverless, Static
**Agregado en:** `@astrojs/vercel@3.3.0`
Opciones de configuración para la [API de Optimización de Imágenes de Vercel](https://vercel.com/docs/concepts/image-optimization). Consulta la [documentación de configuración de imágenes de Vercel](https://vercel.com/docs/build-output-api/v3/configuration#images) para obtener una lista completa de los parámetros admitidos.
@@ -140,7 +134,7 @@ export default defineConfig({
### imageService
**Tipo:** `boolean`
-**Disponible para:** Edge, Serverless, Static
+**Disponible para:** Serverless y Static
**Agregado en:** `@astrojs/vercel@3.3.0`
Cuando está habilitado, se configurará y utilizará automáticamente un [Servicio de Imágenes](/es/reference/image-service-reference/) impulsado por la API de Optimización de Imágenes de Vercel en producción. En desarrollo, se utilizará en su lugar un servicio incorporado basado en Squoosh.
@@ -178,7 +172,7 @@ import astroLogo from ''../assets/logo.png';
### includeFiles
**Tipo:** `string[]`
-**Disponible para:** Edge, Serverless
+**Disponible para:** Serverless
Usa esta propiedad para forzar a que los archivos se incluyan en el empaquetado de tu función. Esto es útil cuando notas que faltan archivos.
@@ -195,10 +189,6 @@ export default defineConfig({
});
```
-:::note
-Cuando se construye para el Edge, todas las dependencias se empaquetan en un solo archivo para ahorrar espacio. **No se empaquetará ningún archivo adicional**. Por lo tanto, si *necesitas* algún archivo dentro de la función, debes especificarlo en `includeFiles`.
-:::
-
### excludeFiles
**Tipo:** `string[]`
@@ -219,9 +209,11 @@ export default defineConfig({
});
```
-### Funciones por página
+### Configuración de agrupación de funciones
-El adaptador de Vercel se construye en una sola función de forma predeterminada. Astro 2.7 agregó soporte para dividir tu compilación en puntos de entrada separados por página. Si usas esta configuración, el adaptador de Vercel generará una función separada para cada página. Esto puede ayudar a reducir el tamaño de cada función para que solo estén empaquetando el código utilizado en esa página.
+El adaptador de Vercel divide las compilaciones en una función separada por ruta de forma predeterminada. Esto ayuda a reducir el tamaño de cada función, ya que solo agrupa el código utilizado en esa página.
+
+Puedes desactivar esto y compilar en una única función configurando la opción de configuración `functionPerRoute` en `false`:
```js
// astro.config.mjs
@@ -230,10 +222,9 @@ import vercel from '@astrojs/vercel/serverless';
export default defineConfig({
output: 'server',
- adapter: vercel(),
- build: {
- split: true,
- },
+ adapter: vercel({
+ functionPerRoute: false,
+ }),
});
```
@@ -270,7 +261,7 @@ Puedes usar el middleware de Vercel Edge para interceptar una solicitud y rediri
El adaptador `@astrojs/vercel/serverless` puede crear automáticamente el middleware de Vercel Edge a partir de un middleware de Astro en tu código base.
-Esto es una característica opcional, y la opción `build.excludeMiddleware` debe establecerse en `true`:
+Esto es una característica opcional, y la opción `edgeMiddleware` debe establecerse en `true`:
```js
// astro.config.mjs
@@ -278,10 +269,9 @@ import { defineConfig } from 'astro/config';
import vercel from '@astrojs/vercel';
export default defineConfig({
output: 'server',
- adapter: vercel(),
- build: {
- excludeMiddleware: true,
- },
+ adapter: vercel({
+ edgeMiddleware: true,
+ }),
});
```
diff --git a/src/content/docs/es/guides/markdown-content.mdx b/src/content/docs/es/guides/markdown-content.mdx
index b52477814b557..59c2106de8cc7 100644
--- a/src/content/docs/es/guides/markdown-content.mdx
+++ b/src/content/docs/es/guides/markdown-content.mdx
@@ -58,60 +58,6 @@ No tiene muchos estilos pero Markdown soporta:
📚 Lee más acerca del [enrutamiento basado en archivos](/es/core-concepts/routing/) u opciones para crear [rutas dinámicas](/es/core-concepts/routing/#rutas-dinámicas).
-### Páginas de borrador
-
-`draft: true` es un valor opcional que marcará una página o artículo individual de Markdown o MDX como "borrador". De forma predeterminada, esta página será:
-- excluida de la compilación final del proyecto (**no se creará ninguna página**)
-- devuelta por [`Astro.glob()`](/es/reference/api-reference/#astroglob) (**visible en listas de artículos**)
-
-```markdown {5}
----
-# src/pages/post/blog-post.md
-layout: ../../layouts/BaseLayout.astro
-title: Mi artículo de blog
-draft: true
----
-
-Este es mi artículo de blog en progreso.
-
-No se creará ninguna página para esta publicación.
-
-Para crear y publicar este artículo:
-
-- actualiza el frontmatter a `draft: false` o
-- elimina la propiedad `draft` por completo.
-
-Pero esta página _sí será_ devuelta por cualquier petición que coincida en `Astro.glob()`.
-```
-
-Para evitar que los borradores sean incluidos en un registro de artículos o en la lista de artículos más recientes, puedes filtrar los resultados devueltos por `Astro.glob()`:
-
-```js
-const posts = await Astro.glob('../pages/post/*.md');
-const nonDraftPosts = posts.filter((post) => !post.frontmatter.draft);
-```
-
-#### Habilitar la creación de páginas de borrador
-
-Para habilitar la creación de páginas de borrador por defecto, actualiza tu `astro.config.mjs` añadiendo `drafts: true` a `markdown` o a la integración `mdx`:
-
-```js title="astro.config.mjs" ins={5, 8}
-import { defineConfig } from 'astro/config';
-
-export default defineConfig({
- markdown: {
- drafts: true,
- },
- integrations: [mdx({
- drafts: true,
- })],
-});
-```
-
-:::tip
-¡También puedes agregar la extensión `--drafts` al ejecutar `astro build` para incluir la creación de páginas borrador!
-:::
-
## Características de Markdown
Astro provee algunas características adicionales incorporadas disponibles a la hora de usar Markdown y archivos MDX.
@@ -182,7 +128,7 @@ Por ejemplo, para prevenir que `<` sea interpretado como el inicio de un element
Añadiendo la [integración de MDX](/es/guides/integrations-guide/mdx/) de Astro vas a potenciar tu autoría de Markdown con variables JSX, expresiones y componentes.
-También añade características extra al MDX estándar, incluyendo soporte para [frontmatter del estilo Markdown en MDX](https://mdxjs.com/guides/frontmatter/). Esto te permite usar la mayoría de las características incorporadas en Astro de Markdown como la propiedad [`layout` en el frontmatter](#layout-en-el-frontmatter) y una configuración para [páginas de borrador](#páginas-de-borrador).
+También añade características extra al MDX estándar, incluyendo soporte para [frontmatter del estilo Markdown en MDX](https://mdxjs.com/guides/frontmatter/). Esto te permite usar la mayoría de las características incorporadas en Astro de Markdown como la propiedad [`layout` en el frontmatter](#layout-en-el-frontmatter).
Los archivos `.mdx` deben ser escritos usando [sintaxis de MDX](https://mdxjs.com/docs/what-is-mdx/#mdx-syntax) en vez de la sintaxis de tipo HTML de Astro.
diff --git a/src/content/docs/es/guides/middleware.mdx b/src/content/docs/es/guides/middleware.mdx
index e1e08f6f430af..01b21062e5b2b 100644
--- a/src/content/docs/es/guides/middleware.mdx
+++ b/src/content/docs/es/guides/middleware.mdx
@@ -45,7 +45,7 @@ Puedes importar y usar la función de utilidad `defineMiddleware()` para aprovec
```ts title="src/middleware.ts"
-import { defineMiddleware } from "astro/middleware";
+import { defineMiddleware } from "astro:middleware";
// `context` y `next` son tipados automáticamente.
export const onRequest = defineMiddleware((context, next) => {
@@ -139,7 +139,7 @@ export const onRequest = async (context, next) => {
Múltiples middlewares pueden ser unidos en un orden específico utilizando [`sequence()`](#sequence):
```js title="src/middleware.js"
-import { sequence } from "astro/middleware";
+import { sequence } from "astro:middleware";
async function validation(_, next) {
console.log("solicitud de validación");
diff --git a/src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx
index f3b39a52638c4..f176ef5c7a79f 100644
--- a/src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx
+++ b/src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx
@@ -87,8 +87,6 @@ Puede resultarte útil instalar algunas de las [integraciones opcionales de Astr
- **@astrojs/react**: para reutilizar algunos componentes UI de React existentes en tu nuevo sitio Astro o seguir escribiendo con componentes de React.
-- **@astrojs/image**: para reemplazar el complemento de imagen de Gatsby con los propios componentes de optimización de imagen de Astro. (Experimental: funciona solo en archivos `.astro` y `.mdx`)
-
- **@astrojs/mdx**: para llevar los archivos MDX existentes de tu proyecto de Gatsby o utilizar MDX en tu nuevo sitio Astro.
@@ -321,36 +319,28 @@ Ver más sobre [Estilizando en Astro](/es/guides/styling/).
### Plugin de imágenes de Gatsby a Astro
-:::note
-Astro v3.0 incluirá un nuevo módulo `astro:assets` y descontinuará la integración existente `@astrojs/image`.
-
-Accede a `astro:assets` actualmente está disponible bajo una flag experimental, y es la forma recomendada de comenzar un nuevo proyecto de Astro. Si estás migrando a Astro pre-v3.0, recomendamos [habilitar la flag experimental para usar assets](/es/guides/assets/) como solución de imagen.
-:::
-
-Convierte los componentes `` y `` de Gatsby con la [integración de imágenes de Astro](/es/guides/images/#integración-image-de-astro), o utiliza una etiqueta HTML `` / JSX `` estándar según corresponda.
+Convierte los componentes `` y `` de Gatsby a [los propios componentes de integración de imágenes de Astro](/es/guides/images/#image--astroassets), o a una etiqueta [estándar de HTML `` / JSX ``](/es/guides/images/#imágenes-en-componentes-de-frameworks-ui) según corresponda en tus componentes de React.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
-Los componentes `` y `` de Astro son experimentales y actualmente solo funcionan en archivos `.astro` y `.mdx` files only. Puedes ver una [lista completa de atributos de componente](/es/guides/integrations-guide/image/#uso) disponibles para estos componentes, y debes tener en cuenta que varios atributos difieren de los atributos de Gatsby.
+El componente `` de Astro funciona solo en archivos `.astro` y `.mdx`. Consulta una [lista completa de sus atributos de componente](/es/guides/images/#propiedades) y ten en cuenta que varios serán diferentes de los atributos de Gatsby.
-Para continuar utilizando imágenes locales en archivos Markdown (`.md`) utilizando la sintaxis estándar de Markdown (`![]()`),mueve tus imágenes a la carpeta `public/`. Es posible que debas actualizar el enlace a la URL relativa. También puedes utilizar la etiqueta `` estándar en estos archivos. Ten en cuenta que estas [imágenes en `public/` no serán optimizadas por Astro](/es/guides/images/#public).
+Para seguir utilizando [imágenes en archivos Markdown (`.md`)](/es/guides/images/#imágenes-en-archivos-markdown) utilizando la sintaxis estándar de Markdown (`![]()`), es posible que necesites actualizar el enlace. El uso de la etiqueta HTML `` no es compatible en archivos `.md` para imágenes locales, y debe ser convertido a la sintaxis de Markdown.
```md
# Mi página Markdown
-
-
-
+
+
```
En componentes de React (`.jsx`), utiliza la sintaxis estándar de JSX para imágenes (``). Astro no optimizará estas imágenes, pero puedes instalar y utilizar paquetes de NPM para obtener más flexibilidad.
diff --git a/src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx
index fa35946ed67cf..d7d5c75291a1d 100644
--- a/src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx
+++ b/src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx
@@ -83,9 +83,6 @@ Puede resultarte útil instalar algunas de las [integraciones opcionales de Astr
- **@astrojs/react**: Para reutilizar algunos de los componentes UI de React existentes en tu nuevo sitio de Astro, o seguir escribiendo con componentes de React.
-- **@astrojs/image**:
-para reemplazar el plugin Image de Next con los propios componentes de optimización de imágenes de Astro. (Experimental: solo funciona en archivos `.astro` y `.mdx`)
-
- **@astrojs/mdx**: Para traer archivos MDX existentes de tu proyecto Next, o para usar MDX en tu nuevo sitio Astro.
### Coloca tu código fuente en `src`
@@ -420,22 +417,17 @@ Ver más acerca de [Estilos en Astro](/es/guides/styling/).
### Plugin de Imagen de Next a Astro
-:::note
-Astro v3.0 incluirá un nuevo módulo `astro:assets` y descontinuará la integración existente `@astrojs/image`.
-
-Accede a `astro:assets` actualmente está disponible bajo una flag experimental, y es la forma recomendada de comenzar un nuevo proyecto de Astro. Si estás migrando a Astro pre-v3.0, recomendamos [habilitar la flag experimental para usar assets](/es/guides/assets/) como solución de imagen.
-:::
+Convierte cualquier componente `` de Next a [el componente de imagen propio de Astro](/es/guides/images/#image--astroassets) en archivos `.astro` o `.mdx`, o a una etiqueta [estándar de HTML `` / JSX ``](/es/guides/images/#imágenes-en-componentes-de-frameworks-ui) según corresponda en tus componentes de React.
-Convierte cualquier componente `` de Next a los [propios componentes de integración de imagen de Astro](/es/guides/images/#integración-image-de-astro), o a un estándar HTML ``. Consulta [la lista completa de los atributos de los componentes](/es/guides/integrations-guide/image/#uso) disponibles para los componentes `` y `` de Astro, y ten en cuenta que varios difieren de los atributos de Next.
+El componente `` de Astro funciona solo en archivos `.astro` y `.mdx`. Consulta una [lista completa de sus atributos de componente](/es/guides/images/#propiedades) y ten en cuenta que varios serán diferentes de los atributos de Next.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
En los componentes de React (`.jsx`), utiliza la sintaxis estándar de imagen (``). Astro no optimizará estas imágenes, pero puedes instalar y usar paquetes de NPM para obtener más flexibilidad.
diff --git a/src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx
index 83e3e8d421a07..ec0dcb116d1c1 100644
--- a/src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx
+++ b/src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx
@@ -106,8 +106,6 @@ Puede resultarte útil instalar algunas de las [integraciones opcionales de Astr
- **@astrojs/vue**: para reutilizar algunos componentes de interfaz de usuario Vue existentes en tu nuevo sitio Astro, o seguir escribiendo con componentes Vue.
-- **@astrojs/image**: para reemplazar el plugin de imagen de Nuxt con los propios componentes de optimización de imagen de Astro.
-
- **@astrojs/mdx**: para traer archivos MDX existentes de tu proyecto Nuxt, o para usar MDX en tu nuevo sitio Astro.
### Coloca tu código fuente en `src`
@@ -513,24 +511,17 @@ Ve más sobre [Estilos en Astro](/es/guides/styling/).
### Plugin de imagen de Nuxt a Astro
-:::note
-Astro v3.0 incluirá un nuevo módulo `astro:assets` y descontinuará la integración existente `@astrojs/image`.
-
-Accede a `astro:assets` actualmente está disponible bajo una flag experimental, y es la forma recomendada de comenzar un nuevo proyecto de Astro. Si estás migrando a Astro pre-v3.0, recomendamos [habilitar la flag experimental para usar assets](/es/guides/assets/) como solución de imagen.
-:::
-
-Convierte cualquier [componente `` o `` de Nuxt](https://image.nuxtjs.org/components/nuxt-img) a [la integración de imagen de Astro](/es/guides/images/#integración-image-de-astro) o a una etiqueta HTML `` estándar.
+Convierte cualquier [componente `` or `` de Nuxt](https://image.nuxtjs.org/components/nuxt-img) al [componente de imagen propio de Astro](/es/guides/images/#image--astroassets) en archivos `.astro` o `.mdx`, o al tag estándar [``](/es/guides/images/#imágenes-en-componentes-de-frameworks-ui) o `` de HTML según corresponda en tus componentes de Vue.
-Mira una [lista completa de atributos de componentes](/es/guides/integrations-guide/image/#uso) disponibles para los componentes `` y `` de Astro, y ten en cuenta que varios serán diferentes a los atributos de Nuxt.
+El componente `` de Astro funciona solo en archivos `.astro` y `.mdx`. Consulta una [lista completa de sus atributos de componente](/es/guides/images/#propiedades) y ten en cuenta que varios serán diferentes de los atributos de Nuxt.
```astro title="src/pages/index.astro"
---
-import { Image } from '@astrojs/image/components';
-import localImage from "../images/brand/logo.png";
-import rocket from '../images/rocket.svg';
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
---
-
-
+
+
```
En los componentes Vue (`.vue`) dentro de tu aplicación Astro, usa la sintaxis de imagen JSX estándar (``). Astro no optimizará estas imágenes, pero puedes instalar y usar paquetes NPM para tener más flexibilidad.
diff --git a/src/content/docs/es/guides/rss.mdx b/src/content/docs/es/guides/rss.mdx
index 61894950b4b17..55e52d0996803 100644
--- a/src/content/docs/es/guides/rss.mdx
+++ b/src/content/docs/es/guides/rss.mdx
@@ -47,12 +47,12 @@ El archivo de ejemplo a continuación `src/pages/rss.xml.js` creará un feed RSS
```js title="src/pages/rss.xml.js"
import rss from '@astrojs/rss';
-export function get(context) {
+export function GET(context) {
return rss({
// `` campo en el xml generado
- title: 'Buzz’s Blog',
+ title: 'Blog de Buzz',
// `` campo en el xml generado
- description: 'A humble Astronaut’s guide to the stars',
+ description: 'Guía de un humilde astronauta a las estrellas',
// Usa el "site" desde el contexto del endpoint
// https://docs.astro.build/en/reference/api-reference/#contextsite
site: context.site,
@@ -60,7 +60,7 @@ export function get(context) {
// Consulta la sección "Generando `items`" para ejemplos utilizando colecciones de contenido y glob imports
items: [],
// (opcional) inyecta xml personalizado
- customData: `en-us`,
+ customData: `es`,
});
}
```
@@ -76,11 +76,11 @@ Puedes generar esta matriz a partir de un esquema de colección de contenido o u
Para crear un RSS feed de páginas manejadas en [colecciones de contenido](/es/guides/content-collections/), utiliza la función `getCollection()` para recuperar la lista de tus artículos.
```js title="src/pages/rss.xml.js" "items:" "const blog = await getCollection('blog');"
-export async function get(context) {
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
- title: 'Buzz’s Blog',
- description: 'A humble Astronaut’s guide to the stars',
+ title: 'Blog de Buzz',
+ description: 'Guía de un humilde astronauta a las estrellas',
site: context.site,
items: blog.map((post) => ({
title: post.data.title,
@@ -120,10 +120,10 @@ Esta función asume, pero no verifica, que todas las propiedades RSS necesarias
```js title="src/pages/rss.xml.js" "pagesGlobToRssItems" "await pagesGlobToRssItems("
import rss, { pagesGlobToRssItems } from '@astrojs/rss';
-export async function get(context) {
+export async function GET(context) {
return rss({
- title: 'Buzz’s Blog',
- description: 'A humble Astronaut’s guide to the stars',
+ title: 'Blog de Buzz',
+ description: 'Guía de un humilde astronauta a las estrellas',
site: context.site,
items: await pagesGlobToRssItems(
import.meta.glob('./blog/*.{md,mdx}'),
@@ -156,15 +156,16 @@ import rss from '@astrojs/rss';
import sanitizeHtml from 'sanitize-html';
import MarkdownIt from 'markdown-it';
const parser = new MarkdownIt();
-export async function get(context) {
+
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
- title: 'Buzz’s Blog',
- description: 'A humble Astronaut’s guide to the stars',
+ title: 'Blog de Buzz',
+ description: 'Guía de las estrellas para un humilde astronauta',
site: context.site,
items: blog.map((post) => ({
link: `/blog/${post.slug}/`,
- // Note: this will not process components or JSX expressions in MDX files.
+ // Nota: esto no procesará componentes ni expresiones JSX en archivos MDX.
content: sanitizeHtml(parser.render(post.body)),
...post.data,
})),
@@ -177,12 +178,12 @@ Cuando utilices imports glob con Markdown, puedes utilizar el helper `compiledCo
```js title="src/pages/rss.xml.js" ins={2, 13}
import rss from '@astrojs/rss';
import sanitizeHtml from 'sanitize-html';
-export function get(context) {
+export function GET(context) {
const postImportResult = import.meta.glob('../posts/**/*.md', { eager: true });
const posts = Object.values(postImportResult);
return rss({
- title: 'Buzz’s Blog',
- description: 'A humble Astronaut’s guide to the stars',
+ title: 'Blog de Buzz',
+ description: 'Guía de un humilde astronauta a las estrellas',
site: context.site,
items: posts.map((post) => ({
link: post.url,
diff --git a/src/content/docs/es/guides/server-side-rendering.mdx b/src/content/docs/es/guides/server-side-rendering.mdx
index 27ed24c5a85f1..c6f1f8c9911bd 100644
--- a/src/content/docs/es/guides/server-side-rendering.mdx
+++ b/src/content/docs/es/guides/server-side-rendering.mdx
@@ -162,7 +162,7 @@ export const prerender = true;
```mdx title="src/pages/mypage.mdx" {5}
---
layout: '../layouts/markdown.astro'
-title: 'My page'
+title: 'Mi página'
---
export const prerender = true;
# Esta es mi página estática, pre-renderizada
@@ -172,7 +172,7 @@ Y para un endpoint:
```js title="src/pages/myendpoint.js" {1}
export const prerender = true;
-export async function get() {
+export async function GET() {
return {
body: JSON.stringify({ message: `Este es mi endpoint estático` }),
};
@@ -185,7 +185,7 @@ Para un sitio principalmente estático configurado como `output: hybrid`, añade
```js title="src/pages/randomnumber.js" {1}
export const prerender = false;
-export async function get() {
+export async function GET() {
let number = Math.random();
return {
body: JSON.stringify({ number, message: `Aquí hay un número al azar: ${number}` }),
diff --git a/src/content/docs/es/guides/styling.mdx b/src/content/docs/es/guides/styling.mdx
index 625e3649c07b4..5d714a8876835 100644
--- a/src/content/docs/es/guides/styling.mdx
+++ b/src/content/docs/es/guides/styling.mdx
@@ -39,10 +39,10 @@ Este CSS:
Se compila en esto:
```astro
@@ -130,7 +130,6 @@ const backgroundColor = "rgb(24 121 78)";
En Astro, los atributos HTML tales como `class` no se pasan automáticamente a los componentes hijos.
-
En cambio, debes aceptar una prop `class` en el componente hijo y aplicársela al elemento raíz. Al desestructurar las props debes renombrarlo, porque `class` es una [palabra clave (o reservada)](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Lexical_grammar#palabras_clave) en JavaScript.
```astro title="src/components/MyComponent.astro" {2,4}
@@ -154,7 +153,7 @@ import MyComponent from "../components/MyComponent.astro"
¡Esto será rojo!
```
-Este patrón te permite estilar componentes hijos directamente. Astro pasará el nombre de la clase local del padre (por ejemplo `astro-HHNQFKH6`) por la propiedad `class` automaticamente, incluyendo el hijo en ámbito del componente padre.
+Este patrón te permite estilar componentes hijos directamente. Astro pasará el nombre de la clase local del padre (p. ej. `astro-hhnqfkh6`) por la propiedad `class` automaticamente, incluyendo el hijo en el ámbito de su padre. Ten en cuenta que este patrón solo funciona cuando tu [opción `scopedStyleStrategy`](/es/reference/configuration-reference/#scopedstylestrategy) está configurada como `'where'` o `'class'`.
:::note[Clases globales de componentes padre]
Debido a que la propiedad `class` incluye al hijo en el ámbito de su padre, es posible que los estilos caigan en cascada de padre a hijo. Para evitar que esto tenga efectos secundarios no deseados, asegúrese de usar nombres de clase únicos en el componente secundario.
@@ -526,23 +525,35 @@ Si usas Tailwind, el [plugin de tipografía](https://tailwindcss.com/docs/typogr
### Control de paquetes
-Cuando Astro genera tu sitio para desplegarlo en producción, combina tu CSS en fragmentos. Cada página de tu sitio es un fragmento separado, y además, el CSS que se comparte entre varias páginas se separa en fragmentos adicionales para su reutilización.
+Cuando Astro genera tu sitio para desplegarlo en producción, minifica y combina tu CSS en fragmentos. Cada página de tu sitio es un fragmento separado, y además, el CSS que se comparte entre varias páginas se separa en fragmentos adicionales para su reutilización.
+
+Sin embargo, cuando varias páginas comparten estilos, algunos fragmentos compartidos pueden volverse muy pequeños. Si se enviaran todos por separado, se generarían muchas solicitudes de hojas de estilo y afectarían el rendimiento del sitio. Por lo tanto, de forma predeterminada, Astro solo vinculará aquellos en tu HTML que tengan un tamaño superior a 4 KB como etiquetas ``, mientras que incluirá en línea los más pequeños en etiquetas `
+```
+
+### Eliminado: Aplanamiento automático del valor de retorno de `getStaticPaths()`
+
+En Astro v2.x, el valor de retorno de [`getStaticPaths()`](/es/reference/api-reference/#getstaticpaths) se aplanaba automáticamente para permitirte devolver un arreglo de arreglos sin errores.
+
+Astro v3.0 elimina el aplanamiento automático del resultado de `getStaticPaths()`.
+
+#### ¿Qué debo hacer?
+
+Si estás devolviendo un arreglo de arreglos en lugar de un arreglo de _objetos_ (como se espera), ahora debes usar `.flatMap` y `.flat` para asegurarte de que estás devolviendo un array plano.
+
+Se proporcionará un [mensaje de error indicando que el valor de retorno de `getStaticPath()` debe ser un arreglo de objetos](/es/reference/errors/invalid-get-static-paths-entry/#qué-salió-mal) si necesitas actualizar tu código.
+
+### Movido: `astro check` ahora requiere un paquete externo
+
+En Astro v2.x, [`astro check`](/es/reference/cli-reference/#astro-check) estaba incluido en Astro por defecto, y sus dependencias estaban empaquetadas en Astro. Esto resultaba en un paquete más grande, independientemente de si usabas o no `astro check`. También evitaba que tuvieras control sobre la versión de TypeScript y el Servidor de Lenguaje de Astro que se utilizaba.
+
+Astro v3.0 mueve el comando `astro check` fuera del núcleo de Astro y ahora requiere un paquete externo `@astrojs/check`. Además, debes instalar `typescript` en tu proyecto para poder usar el comando `astro check`.
+
+#### ¿Qué debo hacer?
+
+Ejecuta el comando `astro check` después de actualizar a Astro v3.0 y sigue las indicaciones para instalar las dependencias requeridas, o bien, instala manualmente `@astrojs/check` y `typescript` en tu proyecto.
+
+### Obsoleto: `build.excludeMiddleware` y `build.split`
+
+En Astro v2.x, `build.excludeMiddleware` y `build.split` se utilizaban para cambiar la forma en que se emitían archivos específicos al usar un adaptador en modo SSR.
+
+Astro v3.0 reemplaza estas opciones de configuración de compilación con nuevas opciones de configuración [para adaptadores SSR](/es/guides/integrations-guide/#integraciones-oficiales) para realizar las mismas tareas: `edgeMiddleware` y `functionPerRoute`.
+
+#### ¿Qué debo hacer?
+
+Actualiza el archivo de configuración de Astro para usar las nuevas opciones **en la configuración del adaptador** directamente.
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import vercel from "@astrojs/vercel/serverless";
+
+export default defineConfig({
+ build: {
+ excludeMiddleware: true
+ },
+ adapter: vercel({
+ edgeMiddleware: true
+ }),
+});
+```
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import netlify from "@astrojs/netlify/functions";
+
+export default defineConfig({
+ build: {
+ split: true
+ },
+ adapter: netlify({
+ functionPerRoute: true
+ }),
+});
+```
+
+### Obsoleto: `markdown.drafts`
+
+En Astro v2.x, la configuración `markdown.drafts` permitía tener páginas en borrador disponibles cuando se ejecutaba el servidor de desarrollo, pero que no se construían en producción.
+
+Astro v3.0 desaconseja esta característica a favor del método de colecciones de contenido para manejar las páginas en borrador mediante filtrado manual, lo que proporciona un mayor control sobre la funcionalidad.
+
+#### ¿Qué debo hacer?
+
+Para seguir marcando algunas páginas en tu proyecto como borradores, [migra a las colecciones de contenido](/es/guides/content-collections/#migrando-desde-el-enrutamiento-basado-en-archivos) y [filtra manualmente las páginas](/es/guides/content-collections/#filtrando-consultas-de-colección) con la propiedad `draft: true` en el frontmatter en lugar de usar la configuración `markdown.drafts`.
+
+### Obsoleto: Retornando un objeto simple en los endpoints
+
+En Astro v2.x, los endpoints podían devolver un objeto simple, que se convertiría en una respuesta JSON.
+
+Astro v3.0 desecha este comportamiento en favor de devolver directamente un objeto `Response`.
+
+#### ¿Qué debo hacer?
+
+Actualiza tus endpoints para devolver directamente un objeto `Response`.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "title": "Blog de Bob" }};
+ return new Response(JSON.stringify({ "title": "Blog de Bob" }));
+}
+```
+
+Si realmente necesitas mantener el formato anterior, puedes usar el objeto `ResponseWithEncoding`, pero será obsoleto en el futuro.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "title": "Blog de Bob" } };
+ return new ResponseWithEncoding({ body: { "title": "Blog de Bob" }});
+}
+```
+
+### Cambiado por defecto: Puerto `3000`
+
+En Astro v2.x, Astro se ejecutaba en el puerto `3000` por defecto.
+
+Astro v3.0 cambia el [puerto por defecto](/es/reference/cli-reference/#--port-number) a `4321`. 🚀
+
+#### ¿Qué debo hacer?
+
+Actualiza cualquier referencia existente a `localhost:3000`, por ejemplo en tests o en tu `README`, para reflejar el nuevo puerto `localhost:4321`.
+
+### Cambiado por defecto: import.meta.env.BASE_URL `trailingSlash`
+
+En Astro v2.x, `import.meta.env.BASE_URL` agregaba por defecto tu configuración [`base`](/es/reference/configuration-reference/#base) con una barra diagonal al final, llamada [trailingSlash](/es/reference/configuration-reference/#trailingslash). `trailingSlash: "ignore"` también agregaba una barra diagonal al final.
+
+En Astro v3.0, ya no se agrega una barra diagonal al final a `import.meta.env.BASE_URL` de forma predeterminada, ni cuando se establece `trailingSlash: "ignore"`. (El comportamiento existente de `base` en combinación con `trailingSlash: "always"` o `trailingSlash: "never"` no ha cambiado).
+
+#### ¿Qué debo hacer?
+
+Si tu configuración `base` ya tiene una barra diagonal al final, no es necesario realizar ningún cambio.
+
+Si tu configuración `base` no tiene una barra diagonal al final, agrega una si deseas preservar el comportamiento anterior por defecto (o `trailingSlash: "ignore"`):
+
+```js title="astro.config.mjs" del={4} ins={5}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ base: 'mi-base',
+ base: 'mi-base/',
+});
+```
+
+### Cambiado por defecto: `compressHTML`
+
+En Astro v2.x, Astro solamente comprimía tu HTML emitido cuando [`compressHTML`](/es/reference/configuration-reference/#compresshtml) se establecía explícitamente como `true`. El valor predeterminado era `false`.
+
+Astro v3.0 ahora comprime automáticamente el HTML emitido por defecto.
+
+#### ¿Qué debo hacer?
+
+Ahora puedes eliminar `compressHTML: true` de tu configuración, ya que este es el nuevo comportamiento predeterminado.
+
+```js title="astro.config.mjs" del={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ compressHTML: true
+})
+```
+
+Ahora debes establecer `compressHTML: false` para desactivar la compresión de HTML.
+
+### Cambiado por defecto: `scopedStyleStrategy`
+
+En Astro v2.x, el valor predeterminado de [`scopedStyleStrategy`](/es/reference/configuration-reference/#scopedstylestrategy) era `"where"`.
+
+Astro v3.0 introduce un nuevo valor por defecto: `"attribute"`. De manera predeterminada, los estilos ahora se aplican utilizando atributos `data-*`.
+
+#### ¿Qué debo hacer?
+
+Para mantener el [ámbito de estilo](/es/guides/styling/#estilos-locales) actual de tu proyecto, actualiza el archivo de configuración al valor predeterminado anterior:
+
+```js title="astro.config.mjs" ins={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ scopedStyleStrategy: "where"
+})
+```
+
+### Cambiado por defecto: `inlineStyleSheets`
+
+En Astro v2.x, todas las hojas de estilo del proyecto se enviaban por defecto como etiquetas de enlace. Podías elegir insertarlas siempre en etiquetas `
```
-### `src/assets/` (実験的)
+### ``
-`/assets/` フォルダの実験的な使用を有効にするには、[アセット(実験的)](/ja/guides/assets/)ガイドを参照してください。
+[Astroテンプレートの構文](/ja/core-concepts/astro-syntax/)では、最終的な出力を完全に制御可能な``タグを直接書くこともできます。これらの画像は処理されず、最適化もされません。
-その場合、既存の画像を更新し、現在のAstro画像インテグレーションを削除する必要があります。また、Astroの新機能の一部を利用するためには、さらに手動での変更が必要になります。
+すべてのHTMLの``タグのプロパティを記述でき、必須のプロパティは`src`のみです。
-## Astro画像インテグレーション
+#### `src/`内のローカル画像
-Astro公式の画像のインテグレーションは、最適化された画像をレンダリングするためのAstroコンポーネント``と``を提供しています。これらのコンポーネントは全ての静的サイトと、[一部のサーバーサイドレンダリングのデプロイホスト](/ja/guides/integrations-guide/image/#installation)をサポートしています。
+ローカル画像は、`.astro`ファイルからの相対パスにより**インポート**するか、[インポートエイリアス](/ja/guides/aliases/)を設定して使用する必要があります。これにより、``タグで使用する画像の`src`やその他のプロパティにアクセスできます。
-[`@astrojs/image`のインストール](/ja/guides/integrations-guide/image/#installation)で、`.astro`と`.mdx`などのAstroコンポーネントを利用できるファイル内でこの2つのコンポーネントを利用できます。
+たとえば、CLSを回避しCore Web Vitalsを改善するために、画像の`height`と`width`プロパティを使用します。
-:::note[アセットの互換性がない]
-アセットの実験的なサポートを有効にしている場合は、公式インテグレーションをアンインストールする必要があります。詳細については、[アセット (実験的) ガイド](/ja/guides/assets/) を参照してください。
-:::
+```astro "myDog.width" "myDog.height"
+---
+// ローカル画像のインポート
+import myDog from `../../images/pets/local-dog.jpg`
+---
+// 画像のプロパティにアクセス
+
+```
-### ``
+インポートされた画像アセットは、以下のシグネチャと一致します。
-Astroの[``コンポーネント](/ja/guides/integrations-guide/image/#image-)は1つの画像を最適化し、幅・高さ・アスペクト比を指定できます。また特定の出力フォーマットに画像を変換できます。
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
-このコンポーネントはディスプレイ間で一貫したサイズを維持したい画像や、画質を厳密にコントロールしたいもの(ロゴなど)に有効です。
+#### `public/`内の画像
-レスポンシブ画像の場合やアートディレクションの場合は、代わりに``コンポーネントを利用します。
+`public/`にある画像の場合は、`src`の値に画像の**publicフォルダを起点としたファイルパス**を使用します。
+
+```astro '"/images/public-cat.jpg"'
+
+```
#### リモート画像
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt)・[`format`](/ja/guides/integrations-guide/image/#format)・サイズ)
+リモート画像の場合は、`src`の値に画像の**フルURL**を使用します。
-``コンポーネントの`src`属性に完全なURLを渡し、`alt`の値を含めます。
+```astro '"https://example.com/remote-cat.jpg"'
+
+```
-``コンポーネントはリモート画像のオリジナルのファイルフォーマットを検知できないため、リモート画像を変換するために出力する`format`(pngやavifなど)を指定する必要があります。
+### ``と``の選択
-``コンポーネントはリモート画像のサイズを認識しないので、コンテンツレイアウトのシフトを回避するために[`width`](/ja/guides/integrations-guide/image/#width)と[`height`](/ja/guides/integrations-guide/image/#height)、またはどちらか1つのサイズと[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio)を指定する必要があります。
+``コンポーネントは、画像を最適化し、また(ローカル画像の場合は)オリジナルのアスペクト比に基づいて幅と高さを推測することでCLSを回避します。ただし、特定のフォーマットのみに対応しており、``要素はなく、`srcset`もサポートしていません。
-[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションです。
+以下のような``コンポーネントを使用できない場合に、HTMLの``要素を使用してください。
+ - サポートされていない画像フォーマット
+ - Astroによる画像の最適化が不要な場合
+ - クライアントサイドで`src`属性に動的にアクセスして変更する場合
-#### `src/`のローカル画像
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt))
+### リモート画像の許可
-フロントマターで画像をインポートして、``コンポーネントの`src`属性へ直接渡します。
+`image.domains`と`image.remotePatterns`を使用して、画像の最適化に使用する、許可された画像ソースのURLドメインとパターンのリストを設定できます。この設定は、外部ソースから画像を表示する際にサイトを保護するために追加の安全性を提供します。
-`alt`は必須ですが[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションで、指定が無ければ画像ファイルのプロパティがデフォルト値として設定されます。
+他のソースからのリモート画像は最適化されませんが、これらの画像に``コンポーネントを使用すると、Cumulative Layout Shift(CLS)を防ぐことができます。
-#### `public/`のローカル画像
+たとえば以下の設定では、`astro.build`からのリモート画像のみが最適化されます。
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src)・[`alt`](/ja/guides/integrations-guide/image/#alt)・[`format`](/ja/guides/integrations-guide/image/#format)・サイズ)
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ domains: ["astro.build"],
+ }
+});
+```
-コンポーネントの`src`属性に公開フォルダからの相対パスを渡し、`alt`に値を含めます。
+以下の設定では、HTTPSホストからのリモート画像のみが許可されます。
-これはリモート画像として扱われ、[`width`](/ja/guides/integrations-guide/image/#width)と[`height`](/ja/guides/integrations-guide/image/#height)の両方の属性か、またはどちらか1つのサイズと[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio)属性が必須です。
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ remotePatterns: [{ protocol: "https" }],
+ }
+});
+```
-画像を変換するための`format`属性値が必要です。(pngやavifなど)
+## CMSやCDNの画像の使用
-[その他の属性](/ja/guides/integrations-guide/image/#image-)はオプションです。
+画像CDNは、Astroのすべての画像オプションと互換性があります。``コンポーネント、``タグ、またはMarkdown記法の`src`属性に、画像のフルURLを指定してください。リモート画像の最適化には、[許可されたドメインまたはURLパターンを設定](#リモート画像の許可)する必要があります。
-元画像は`public/`にある他のファイルと同じくビルドフォルダーにそのままコピーされ、Astroの画像インテグレーションは最適化された画像を返します。
+あるいは、CDNがNode.js SDKを提供している場合は、プロジェクトでそれを使用することも可能です。たとえば[CloudinaryのSDK](https://cloudinary.com/documentation/node_integration)は、適切な`src`をもつ``タグを生成してくれます。
-#### 例
+## Markdownファイル内の画像
-```astro
+`.md`ファイルでは、Markdown標準の``構文を使用します。この構文は、Astroの[画像サービスAPI](/ja/reference/image-service-reference/)と連携して、ローカル画像と許可されたリモート画像を最適化します。
+
+```md
+
+
+# 私のMarkdownページ
+
+
+
+
+
+
+
+
+
+
+
+
+```
+
+ローカル画像の場合``タグはサポートされておらず、また`.md`ファイルでは``コンポーネントは使用できません。
+
+画像の属性をより細かく制御する必要がある場合は、Markdown構文に加えて、Astroの``コンポーネントや、JSXの``タグを使用可能な`.mdx`ファイル形式を使用することをおすすめします。AstroにMDXサポートを追加するには、[MDXインテグレーション](/ja/guides/integrations-guide/mdx/)を使用します。
+
+## MDXファイル内の画像
+
+コンポーネントと画像をインポートすることで、`.mdx`ファイル内でAstroの``コンポーネントとJSXの``タグを使用できます。使い方は[`.astro`ファイルの場合](#astroファイル内の画像)と同様です。
+
+さらに、インポート不要で[Markdown標準の``構文](#markdownファイル内の画像)もサポートされています。
+
+```mdx title="src/pages/post-1.mdx"
---
-// src/pages/index.astro
-import { Image } from '@astrojs/image/components';
-import localImage from "../assets/logo.png";
-const remoteImage = "https://picsum.photos/id/957/300/200.jpg";
-const localAlt = "The Astro Logo";
-const remoteAlt = "A low-angle view of a forest during the daytime";
+title: 私のページタイトル
---
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
+
+# 私のMDXページ
-
-
+// src/assets/に置かれたローカル画像
+
+
+
-
-
+// public/images/に置かれた画像
+
+
+
-
-
+// 別のサーバー上のリモート画像
+
+
+
-
-
-
+```
+
+## コンテンツコレクションと画像
-
-
-
+ブログ記事のカバー画像など、コンテンツコレクションのエントリに関連付けられた画像を、現在のフォルダからの相対パスを使ってフロントマターに宣言できます。
-
-
+```md title="src/content/blog/my-post.md" {3}
+---
+title: "私の最初のブログ記事"
+cover: "./firstpostcover.jpeg" # "src/content/blog/firstblogcover.jpeg"へと解決されます
+coverAlt: "山々の向こうに沈む夕日の写真。"
+---
-
-
+これはブログ記事です
```
-### ` `
+コンテンツコレクションスキーマの`image`ヘルパーにより、Zodを使用して画像のメタデータを検証できます。
-Astroの[``コンポーネント](/ja/guides/integrations-guide/image/#picture-)は複数の画像サイズ・フォーマット・レイアウトなど、サイト上でレスポンシブな画像を提供するために利用できます。
+```ts title="src/content/config.ts"
+import { defineCollection, z } from "astro:content";
-画面サイズや帯域幅に基づいて、画像に最適なサイズ、解像度、ファイルタイプを利用ユーザーのブラウザに任せることができます。また、メディアクエリに基づいてブラウザに従わせるルールを指定できます。
+const blogCollection = defineCollection({
+ schema: ({ image }) => z.object({
+ title: z.string(),
+ cover: image().refine((img) => img.width >= 1080, {
+ message: "カバー画像は幅1080ピクセル以上でなければなりません!",
+ }),
+ coverAlt: z.string(),
+ }),
+});
-このコンポーネントは、ユーザーが様々な画面サイズで見る画像を最適化するためや、アートディレクションに最適です。
+export const collections = {
+ blog: blogCollection,
+};
+```
-:::tip
-[レスポンシブ画像とアートディレクション](https://developer.mozilla.org/ja/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#%E3%82%A2%E3%83%BC%E3%83%88%E3%83%87%E3%82%A3%E3%83%AC%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3)の詳細はMDNのガイドを参照してください。
-:::
+画像はインポートされ、メタデータへと変換されます。これにより、``、``、そして`getImage()`に、`src`として渡すことができます。
-#### リモート画像
+以下の例は、上記のスキーマから各ブログ記事のカバー写真とタイトルをレンダリングする、ブログのインデックスページを示しています。
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1)・[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio-1))
+```astro title="src/pages/blog.astro" {10}
+---
+import { Image } from "astro:assets";
+import { getCollection } from "astro:content";
+const allBlogPosts = await getCollection("blog");
+---
-完全なURLを``コンポーネントの`src`属性へ渡します。
+{
+ allBlogPosts.map((post) => (
+
+ ))
+}
+```
+
+## UIフレームワークコンポーネント内の画像
+
+UIフレームワークコンポーネントに画像を追加する場合は、フレームワーク独自の画像構文を使用して画像をレンダリングします(たとえば、JSXの``、Svelteの``などです)。
-またビルド時に正しい高さを計算できるようにリモート画像は`aspectRatio`も必要になります。
+ローカル画像は、`src`などの[画像プロパティ](#src内のローカル画像)にアクセスするために**最初にインポート**する必要があります。
-画像の幅と画面サイズに関する指示をコンポーネントに与える必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+```jsx title="src/components/ReactImage.jsx"
+import stars from "../assets/stars.png"
-[`formats`](/ja/guides/integrations-guide/image/#formats)は必須ではありませんが、リモート画像の元のフォーマットが不明となりデフォルト値は含まれません。何も指定が無ければ、`webp`と`avif`だけが含まれます。
+export default function ReactImgage () {
+ return (
+
+ )
+}
+```
-#### ローカル画像
+```svelte title="src/components/SvelteImage.svelte"
+
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1))
+
-フロントマターで画像をインポートして、``コンポーネントの`src`属性へ直接渡します。
+```
-画像の幅と画像のガイダンスをコンポーネントへ渡す必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+#### Imageコンポーネントを渡す
-``コンポーネントの[`formats`](/ja/guides/integrations-guide/image/#formats)に指定がなければ、デフォルト値は元の画像のフォーマットに加えて`avif`と`webp`が含まれます。
+``コンポーネントは、他のAstroコンポーネントと同様に、**UIフレームワークコンポーネントでは使用できません**。
-#### `public/`の画像
+しかし、`.astro`ファイル内のフレームワークコンポーネントに、``によって生成された静的コンテンツを子要素として渡すか、または[名前付きの``](/ja/core-concepts/framework-components/#フレームワークコンポーネントの中でastroコンポーネントを使用できますか)を使用して渡すことは可能です。
-(必須属性: [`src`](/ja/guides/integrations-guide/image/#src-1)・[`widths`](/ja/guides/integrations-guide/image/#widths)・[`sizes`](/ja/guides/integrations-guide/image/#sizes)・[`alt`](/ja/guides/integrations-guide/image/#alt-1)・[`aspectRatio`](/ja/guides/integrations-guide/image/#aspectratio-1))
-コンポーネントの`src`属性にはpublicフォルダからの相対パスを渡し、`alt`の値を必要とします。
+```astro title="ImageWrapper.astro"
+---
+import ReactComponent from './ReactComponent.jsx';
+import { Image } from "astro:assets"
+import stars from "~/stars/docline.png";
+---
-画像はリモート画像として扱われるため、ビルド時に正しい高さを計算できるように`aspectRatio`の指定が必要です。
+
+
+
+```
-画像の幅と画面サイズに関する指示をコンポーネントに与える必要がありますが、[その他の属性](/ja/guides/integrations-guide/image/#picture-)はオプションです。
+## `getImage()`で画像を生成する
-[`formats`](/ja/guides/integrations-guide/image/#formats)は必須ではありませんが、`public/`フォルダにある画像の元のフォーマットが不明となりデフォルト値は含まれません。何も指定が無ければ、`webp`と`avif`だけが含まれます。
+:::caution
+`getImage()`はサーバー専用のAPIに依存しており、クライアントで使用するとビルドが失敗します。
+:::
-元の画像は`public/`にある他のファイルと同じくビルドフォルダーにそのままコピーされ、Astroの画像インテグレーションは最適化された画像を返します。
+`getImage()`関数は、たとえば[APIルート](/ja/core-concepts/endpoints/#サーバーエンドポイントapiルーティング)など、HTML以外の場所で使用する画像を生成することを目的としています。また、これを使って独自のカスタム``コンポーネントも作成できます。
-#### 例
+`getImage()`は、(`alt`を除く)[Imageコンポーネントと同じプロパティ](#プロパティ)をもつオプションオブジェクトを受け取ります。
```astro
---
-import { Picture } from '@astrojs/image/components';
-import localImage from '../assets/logo.png';
-const remoteImage = 'https://docs.astro.build/assets/full-logo-light.png';
+import { getImage } from "astro:assets";
+import myBackground from "../background.png"
+
+const optimizedBackground = await getImage({src: myBackground, format: 'avif'})
---
-
-
+
+```
+
+`getImage()`は以下のプロパティをもつオブジェクトを返します。
+
+```js
+{
+ options: {...} // 渡されたオリジナルのパラメータ
+ src: "https//..." // 生成された画像へのパス
+ attributes: {...} // 画像をレンダリングするために必要な追加のHTML属性(width、height、styleなど)
+}
+```
+
+## 代替テキスト
+
+すべてのユーザーが同じように画像を見れるわけではないため、画像を使用する際のアクセシビリティは特に重要です。画像に対して[説明的な代替テキスト](https://www.w3.org/WAI/tutorials/images/)を提供するために、`alt`属性を使用してください。
+
+この属性は``コンポーネントでは必須です。代替テキストが指定されていない場合、``はエラーをスローします。
+
+画像が単に装飾用である場合(つまり、ページの理解に貢献していない場合)は、`alt=""`を設定して、スクリーンリーダーが画像を無視するようにしてください。
-
-
+## デフォルトの画像サービス
-
-
+[Sharp](https://github.com/lovell/sharp)は、`astro:assets`で使用されるデフォルトの画像サービスです。
-
-
+画像を変換するために[Squoosh](https://github.com/GoogleChromeLabs/squoosh)を使用したい場合は、以下のように設定を更新してください。
+```js title="astro.config.mjs" ins={4-6}
+import { defineConfig, squooshImageService } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+});
```
-### MDXでの利用
+## コミュニティインテグレーション
-`.mdx`ファイル内では、インポートとエクスポートを通して``と``が画像の`src`を受け取ることができます。
+Astroプロジェクトで画像を最適化したり、画像を扱ったりするための、サードパーティの[コミュニティインテグレーション](https://astro.build/integrations?search=images)があります。
-```mdx
-// src/pages/index.mdx
+## v2.xからv3.0へのアップグレード
-import { Image, Picture } from '@astrojs/image/components';
-import rocket from '../assets/rocket.png';
-export const logo = 'https://docs.astro.build/assets/full-logo-light.png';
+Astro v3.0では、`astro:assets`は実験的な機能ではなくなりました。
+
+``は組み込みのコンポーネントとなり、以前の`@astrojs/image`インテグレーションは削除されました。
+
+これらのことと、Astroで画像を使用するためのその他の変更により、以前のバージョンからAstroプロジェクトをアップグレードすると、いくつかの破壊的な変更が発生する可能性があります。
+
+Astro v2.xプロジェクトをv3.0にアップグレードするには、以下の手順に適切に従ってください。
+
+### `experimental.assets`からのアップグレード
+
+以前に`astro:assets`の実験的なフラグを有効にしていた場合は、Astro v3.0ではデフォルトでアセット機能が含まれているため、プロジェクトを更新する必要があります。
+
+#### `experimental.assets`フラグの削除
+
+実験的なフラグを削除します。
+
+```js title="astro.config.mjs" del={4-6}
+import { defineConfig } from 'astro/config';
-
-
-
-
+export default defineConfig({
+ experimental: {
+ assets: true
+ }
+});
```
-### デフォルト値を設定する
+必要に応じて、`astro/client-image`への参照を`astro/client`に置き換えるために、`src/env.d.ts`ファイルも更新します。
-現在、``と``コンポーネントにデフォルト値を指定する方法はありません。必須属性はそれぞれのコンポーネントに設定する必要があります。
+```ts title="src/env.d.ts" del={1} ins={2}
+///
+///
+```
-代わりの方法として、再利用できるよう他のAstroコンポーネントでこれらのコンポーネントをラッピングできます。例えば、以下のようにブログ記事画像をコンポーネントとして作成できます。
+#### `~/assets`インポートエイリアスの削除
-```astro title="src/components/BlogPostImage.astro"
----
-import { Picture } from '@astrojs/image/components';
+このImportエイリアスは、`astro:assets`にデフォルトで含まれなくなりました。実験的なアセット機能でこのエイリアスを使用していた場合は、相対ファイルパスに変換するか、[自分でImportエイリアスを作成](/ja/guides/aliases/)する必要があります。
-const {src, ...attrs} = Astro.props;
+```astro title="src/pages/posts/post-1.astro" del={2} ins={3}
+---
+import rocket from '~/assets/rocket.png'
+import rocket from '../../assets/rocket.png';
---
-
+```
-
+});
```
-### 画像インテグレーションで``を使う
+### 画像を保存する場所を決める
+
+[画像を保存する場所](#画像を保存する場所)を決めるには、今読んでいるこのガイドを参照してください。`astro:assets`がもたらす柔軟性を活用して、画像を保存するための新しいオプションを利用したい場合があるかもしれません。たとえば、プロジェクトの`src/`からの相対画像は、Markdown、MDX、MarkdocいずれにおいてもMarkdown標準の``構文により参照できるようになりました。
+
+### 既存の``タグを更新する
+
+以前は画像をインポートすると、画像のパスを含む単純な`string`が返されました。現在は、インポートされた画像アセットは以下のシグネチャをもつオブジェクトとなります。
-公式の画像インテグレーションにより、画像のインポートはソース文字列ではなくオブジェクトを返すように変更されます。このオブジェクトは、インポートされたファイルから派生した以下のプロパティを持ちます。
```ts
-{
+interface ImageMetadata {
src: string;
width: number;
height: number;
- format: 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp';
+ format: string;
}
```
-画像インテグレーションがインストールされている場合は、``を使用する際にオブジェクトの`src`プロパティを参照してください。
+([UIフレームワークコンポーネント内の画像](#uiフレームワークコンポーネント内の画像)を含む)既存の``タグの`src`属性の更新が必要です。また、インポートした画像から利用できるようになった他の属性も更新できます。
-```astro ".src"
+```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={4} ins={6}
---
import rocket from '../images/rocket.svg';
---
-
+
+
+
```
-あるいは、インポートに`?url`を追加して、ソース文字列を返すように指示する。
+### Markdown、MDX、Markdocファイルを更新する
-```astro "?url"
----
-import rocket from '../images/rocket.svg?url';
----
-
+プロジェクトの`src/`からの相対画像は、Markdown、MDX、MarkdocいずれにおいてもMarkdown標準の``構文により参照できるようになりました。
+
+これにより、画像を`public/`ディレクトリからプロジェクトの`src/`に移動し、処理を加えて最適化できます。`public/`内の既存の画像とリモート画像は引き続き有効ですが、Astroのビルドプロセスでは最適化されません。
+
+```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/"
+# 私のMarkdownページ
+
+
+
+
+
+
```
-## CMSやCDN上の画像利用
+画像の属性をより細かく制御する必要がある場合は、Markdown構文に加えて、Astroの``コンポーネントやJSXの``タグを使用可能な`.mdx`ファイル形式を使用することをおすすめします。AstroにMDXサポートを追加するには、[MDXインテグレーション](/ja/guides/integrations-guide/mdx/)を使用します。
+
+### `@astrojs/image`を削除する
+
+
+Astro v2.xで画像インテグレーションを使用していた場合は、以下の手順を完了させてください。
+
+1. `@astrojs/image`を削除します。
+
+ [インテグレーションを削除する](/ja/guides/integrations-guide/#インテグレーションを削除する)ためにアンインストールし、また`astro.config.mjs`ファイルからも削除する必要があります。
+
+ ```js del={3,7}
+ // astro.config.mjs
+ import { defineConfig } from 'astro/config';
+ import image from '@astrojs/image';
+
+ export default defineConfig({
+ integrations: [
+ image(),
+ ]
+ })
+ ```
+
+2. 既存の``コンポーネントを移行します。
+
+ 新しい組み込みの``コンポーネントを使用するために、`@astrojs/image/components`からの`import`文をすべて`astro:assets`に変更します。
+
+ [現在サポートされていない画像アセットのプロパティ](#プロパティ)を削除します。
+
+ たとえば、`aspectRatio`はもうサポートされていません。これは、`width`と`height`属性から自動的に推測されるためです。
+
+ ```astro title="src/components/MyComponent.astro" del= {2,11} ins={3}
+ ---
+ import { Image } from '@astrojs/image/components';
+ import { Image } from 'astro:assets'
+ import localImage from "../assets/logo.png";
+ const localAlt = "Astroのロゴ";
+ ---
+
+
+ ```
+
+3. 既存の``コンポーネントを削除します。
+
+ 現在、組み込みのアセット機能には``コンポーネントは含まれていません。
-CDNネットワーク上の画像をAstroで利用するには、画像の完全なURLを``タグやMarkdownの`src`属性として利用します。
+ 代わりに、HTMLの画像属性`srcset`と`sizes`、または``タグを使用して、[アートディレクションやレスポンシブ画像を作成](https://developer.mozilla.org/ja/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#アートディレクション)できます。
-代わりに、もしCDNがNode.js SDKを提供している場合はプロジェクトでSDKを利用できます。例えば、[CloudinaryのSDK](https://cloudinary.com/documentation/node_integration)は適切な`src`を利用して``タグを生成できます。
+4. デフォルトの画像サービスを選択します。
-Astroの画像インテグレーションの[``を用いた外部画像](#リモート画像)や[``](#リモート画像-1)コンポーネントを利用するには、リモート画像を扱うための適切なサイズとフォーマットを指定する必要があります。
+ [Sharp](https://github.com/lovell/sharp)は、`astro:assets`で使用されるデフォルトの画像サービスとなりました。Sharpを使用する場合は、特に設定は必要ありません。
-## Altテキスト
+ 画像を変換するために[Squoosh](https://github.com/GoogleChromeLabs/squoosh)を使用したい場合は、以下の`image.service`オプションを使用して設定を更新します。
-画像が誰も同じように見えるわけではないため、画像を扱う上でアクセシビリティは特に重要になります。`alt`属性は画像に[Altテキストによる記述](https://www.w3.org/WAI/tutorials/images/)を与えます。
+ ```js title="astro.config.mjs" ins={4-6}
+ import { defineConfig, squooshImageService } from 'astro/config';
-この属性は画像インテグレーションの``と``コンポーネントには必須です。Altテキストが指定されていない場合これらのコンポーネントはエラーを投げます。
+ export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+ });
+ ```
-画像が単なる飾り(ページの理解に貢献しない画像)の場合、スクリーンリーダーが画像を無視するように`alt=""`を設定します。
+### コンテンツコレクションのスキーマを更新する
-## コミュニテーインテグレーション
+ブログ記事のカバー画像など、コンテンツコレクションのエントリに関連付けられた画像を、現在のフォルダからの相対パスによりフロントマターに宣言できるようになりました。
-公式の[`@astrojs/image`](/ja/guides/integrations-guide/image/)インテグレーションに加え、Astroプロジェクトで画像の最適化や処理を行うためのサードパーティー製の[コミュニティー画像インテグレーション](https://astro.build/integrations?search=images)がいくつかあります。
+コンテンツコレクションの新しい`image`ヘルパーにより、Zodを使用して画像のメタデータを検証できるようになりました。コンテンツコレクションで画像を使用する方法について、詳しくは[こちら](#コンテンツコレクションと画像)を参照してください。
diff --git a/src/content/docs/ja/guides/integrations-guide.mdx b/src/content/docs/ja/guides/integrations-guide.mdx
index 8d56bab55e1ad..93d658208c19d 100644
--- a/src/content/docs/ja/guides/integrations-guide.mdx
+++ b/src/content/docs/ja/guides/integrations-guide.mdx
@@ -1,5 +1,5 @@
---
-title: インテグレーションを使う
+title: インテグレーションを追加する
i18nReady: true
---
import IntegrationsNav from '~/components/IntegrationsNav.astro';
@@ -24,10 +24,6 @@ import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'
Astroには、インテグレーションのセットアップを自動化するための`astro add`コマンドが含まれています。
-:::caution
-ファイルを更新する前に必ず確認がありますが、念のためバージョン管理されたバックアップを用意しておくに越したことはないでしょう。
-:::
-
好みのパッケージマネージャーを使用して`astro add`コマンドを実行すると、インテグレーション用の自動ウィザードが設定ファイルの更新と必要な依存関係のインストールを行います。
@@ -48,7 +44,7 @@ Astroには、インテグレーションのセットアップを自動化する
-複数のインテグレーションを同時に設定することも可能です。
+複数のインテグレーションを同時に追加することも可能です。
@@ -123,6 +119,42 @@ integrations: [
]
```
+## インテグレーションを削除する
+
+インテグレーションを削除するには、まずプロジェクトからインテグレーションをアンインストールします。
+
+
+
+ ```shell
+ npm uninstall @astrojs/react
+ ```
+
+
+ ```shell
+ pnpm uninstall @astrojs/react
+ ```
+
+
+ ```shell
+ yarn remove @astrojs/react
+ ```
+
+
+
+続いて、`astro.config.*`ファイルからインテグレーションを削除します。
+
+```js title="astro.config.mjs" del={3,7}
+import { defineConfig } from 'astro/config'
+
+import react from "@astrojs/react";
+
+export default defineConfig({
+ integrations: [
+ react()
+ ]
+})
+```
+
## 他のインテグレーションを見つける
[Astroインテグレーションのリスト](https://astro.build/integrations/)には、コミュニティによって開発された多くのインテグレーションが掲載されています。詳細な使い方や設定方法については、上のリンクをたどってみてください。
diff --git a/src/content/docs/ja/guides/middleware.mdx b/src/content/docs/ja/guides/middleware.mdx
index 073f67492a547..501cf83d09dc8 100644
--- a/src/content/docs/ja/guides/middleware.mdx
+++ b/src/content/docs/ja/guides/middleware.mdx
@@ -44,7 +44,7 @@ const data = Astro.locals;
```ts
// src/middleware.ts
-import { defineMiddleware } from "astro/middleware";
+import { defineMiddleware } from "astro:middleware";
// `context`と`next`は自動的に型付けされます
export const onRequest = defineMiddleware((context, next) => {
@@ -136,7 +136,7 @@ export const onRequest = async (context, next) => {
[`sequence()`](#sequence)を使用して、複数のミドルウェアを指定した順序で連結できます。
```js title="src/middleware.js"
-import { sequence } from "astro/middleware";
+import { sequence } from "astro:middleware";
async function validation(_, next) {
console.log("validationリクエスト");
diff --git a/src/content/docs/ja/guides/styling.mdx b/src/content/docs/ja/guides/styling.mdx
index 5e8ee3b4186ed..87fa3b78e8b46 100644
--- a/src/content/docs/ja/guides/styling.mdx
+++ b/src/content/docs/ja/guides/styling.mdx
@@ -41,10 +41,10 @@ Astroの`
@@ -157,7 +157,7 @@ import MyComponent from "../components/MyComponent.astro"
This will be red!
```
-このパターンでは、子コンポーネントに直接スタイルを設定できます。Astroは、親のスコープ付きクラス名(例:`astro-HHNQFKH6`)を`class`プロパティを通して自動的に渡し、その子を親のスコープに含めます。
+このパターンでは、子コンポーネントに直接スタイルを設定できます。Astroは、親のスコープ付きクラス名(例:`astro-hhnqfkh6`)を`class`プロパティを通して自動的に渡し、その子を親のスコープに含めます。
:::note[親コンポーネントからスコープされたクラス]
`class`プロパティは親のスコープに子を含むので、親から子へスタイルがカスケードされる可能性があります。このような意図しない副作用を避けるには、子コンポーネントでユニークなクラス名を使用するようにします。
@@ -431,9 +431,22 @@ import "../components/make-it-purple.css"
## CSSインテグレーション
-Astroには、[Tailwind][tailwind]など、人気のCSSライブラリやツール、フレームワークをプロジェクトに追加するための仕組みがあります!
+Astroには、[Tailwind](https://tailwindcss.com)など、人気のCSSライブラリやツール、フレームワークをプロジェクトに追加するための仕組みがあります!
+
+### Tailwind
-📚 これらのインテグレーションのインストール、インポート、設定の手順については、[インテグレーションガイド](/ja/guides/integrations-guide/)を参照してください。
+プロジェクトでTailwindを使用するには、公式の[Astro Tailwindインテグレーション][tailwind]を、パッケージマネージャーの`astro add`コマンドを使ってインストールします。
+
+```sh
+# NPMを使う
+npx astro add tailwind
+# Yarnを使う
+yarn astro add tailwind
+# PNPMを使う
+pnpm astro add tailwind
+```
+
+📚 Astroインテグレーションのインストール、インポート、設定の手順については、[インテグレーションガイド](/ja/guides/integrations-guide/)を参照してください。
## CSSプリプロセッサ
@@ -514,6 +527,41 @@ Astroのスタイル方法は、[Markdownレイアウトコンポーネント](/
Tailwindを使用している場合、Markdownのスタイリングには[typographyプラグイン](https://tailwindcss.com/docs/typography-plugin)が便利です。
+## 本番環境
+
+### バンドルの調整
+
+Astroが本番環境向けにサイトをビルドする際、CSSはミニファイされチャンクへと結合されます。サイト上の各ページはそれぞれ独自のチャンクを取得し、さらに複数のページ間で共有されるCSSは、再利用のために独自のチャンクに分割されます。
+
+しかし、複数のページでスタイルを共有している場合、共有される一部のチャンクが非常に小さくなる場合があります。それらがすべて別々に送信された場合、スタイルシートへのリクエストが増加し、サイトのパフォーマンスに影響を与える可能性があります。そのため、Astroはデフォルトでは、HTML内の4kB以上のスタイルシートのみを``タグとしてリンクし、それ以外のものは`
+```
+
+### ``
+
+A [sintaxe de templates do Astro](/pt-br/core-concepts/astro-syntax/) também suporta escrever uma tag `` diretamente, com controle total sobre seu resultado final. Essas imagens não serão processadas e otimizadas.
-
-
+Ela aceita todas as propriedades da tag `` do HTML, e a única propriedade obrigatória é `src`.
+
+#### Imagens locais em `src/`
+
+Imagens locais devem ser **importadas de seu caminho relativo** a partir do arquivo `.astro` existente, ou configure e utilize um [atalho de importação](/pt-br/guides/aliases/). Então, você pode acessar o `src` da imagem e outras propriedades para utilizar na tag ``.
+
+Por exemplo, utilize as propriedades `height` e `width` da imagem para evitar CLS e melhorar os Core Web Vitals.
+
+```astro "meuCachorro.width" "meuCachorro.height"
+---
+// importe imagens locais
+import meuCachorro from `../../imagens/pets/cachorro-local.jpg`
+---
+// acesse propriedades da imagem
+
```
-### Em arquivos Markdown
+Assets de imagem importadas correspondem a seguinte assinatura:
-Você pode utilizar a sintaxe `![]()` padrão do Markdown ou tags `` padrão do HTML em seus arquivos `.md` para imagens localizadas no seu diretório `public/` ou imagens remotas em outro servidor.
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
-Se você não consegue manter suas imagens em `public/`, nós recomendamos habilitar o [suporte experimental para assets](/pt-br/guides/assets/), ou utilizar o formato de arquivo `.mdx`, que permite que você combine componentes importados com sintaxe estilo Markdown. Use a [integração MDX](/pt-br/guides/integrations-guide/mdx/) para adicionar suporte a MDX no Astro.
+#### Imagens em `public/`
+
+Para imagens localizadas em `public/` utilize o **caminho do arquivo relativo a pasta public** da imagem como o valor `src`:
+
+```astro '"/imagens/gato-em-public.jpg"'
+
+```
+
+#### Imagens remotas
+
+Para imagens remotas, utilize a **URL completa** da imagem como o valor de `src`:
+
+```astro '"https://exemplo.com/gato-remoto.jpg"'
+
+```
+
+### Escolhendo `` vs ``
+
+O componente `` otimiza sua imagem e infere a largura e altura (de imagens locais) com base na proporção de tela original para evitar CLS. Porém, ele apenas funciona com certos formatos e não fornece um elemento ``, nem suporta `srcset`.
+
+Utilize o elemento `` do HTML quando você não pode utilizar o componente ``, por exemplo:
+ - para formatos de imagem não suportados
+ - quando você não quer que sua imagem seja otimizada pelo Astro
+ - para acessar e modificar o atributo `src` dinamicamente no lado do cliente
+
+
+### Autorizando imagens remotas
+
+Você pode configurar listas de domínios e padrões de URL fonte de imagens autorizadas para otimização de imagem utilizando [`image.domains`](/pt-br/reference/configuration-reference/#imagedomains) e [`image.remotePatterns`](/pt-br/reference/configuration-reference/#imageremotepatterns). Essa configuração é uma camada adicional de segurança para proteger seu site ao mostrar imagens de uma fonte externa.
+
+Imagens remotas de outras fontes não serão otimizadas, mas utilizando o componente `` para essas imagens irá prevenir Cumulative Layout Shift (CLS).
+
+Por exemplo, a seguinte configuração irá apenas permitir imagens remotas de `astro.build` a serem otimizadas:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ domains: ["astro.build"],
+ }
+});
+```
+
+A seguinte configuração irá apenas permitir imagens remotas de hospedagens HTTPS:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ remotePatterns: [{ protocol: "https" }],
+ }
+});
+```
+
+## Utilizando Imagens de CMS ou CDN
+
+CDNs de imagem funcionam com todas as opções de imagem do Astro. Utilize a URL completa de uma imagem como o atributo `src` no componente ``, em uma tag ``, ou na notação do Markdown. Para otimização de imagem com imagens remotas, também [configure seus domínios e padrões de URL autorizados](#autorizando-imagens-remotas).
+
+Alternativamente, se o CDN fornece um SDK para Node.js, você pode utilizá-lo em seu projeto. Por exemplo, o [SDK da Cloudinary](https://cloudinary.com/documentation/node_integration) pode gerar uma tag `` com o `src` apropriado para você.
+
+## Imagens em arquivos Markdown
+
+Utilize a sintaxe padrão do Markdown `` em seus arquivos `.md`. Essa sintaxe funciona com a [API de Serviço de Imagem](/pt-br/reference/image-service-reference/) do Astro para otimizar suas imagens locais e imagens remotas autorizadas.
```md
-
+
# Minha Página Markdown
-
-
-
+
+
+
+
+
+
+
-
-
+
+
```
-### Em arquivos MDX
+A tag `` não é suportada para imagens locais, e o componente `` está indisponível em arquivos `.md`.
-Você pode utilizar a sintaxe `![]()` padrão do Markdown ou tags `` do JSX em seus arquivos `.mdx` para mostrar imagens do seu diretório `public/` ou de servidores remotos.
+Se você precisa de mais controle sobre seus atributos da imagem, nós recomendamos utilizar o formato de arquivo `.mdx`, que te permite incluir o componente `` do Astro ou uma tag `` JSX em adição a sintaxe do Markdown. Utilize a [integração MDX](/pt-br/guides/integrations-guide/mdx/) para adicionar suporte para MDX ao Astro.
-Adicionalmente, você pode importar e utilizar imagens localizadas no diretório `src/` do seu projeto, assim como você faria em componentes Astro.
+## Imagens em arquivos MDX
-```mdx title="src/pages/post-1.mdx"
+Você pode utilizar o componente `` do Astro e tags `` JSX em seus arquivos `.mdx` importando ambos o componente e sua imagem. Utilize-os assim como eles são [utilizados em arquivos `.astro`](#imagens-em-arquivos-astro).
-import foguete from '../imagens/foguete.svg';
+Adicionalmente, há suporte para [sintaxe padrão do Markdown ``](#imagens-em-arquivos-markdown) com nenhuma importação necessária.
+
+```mdx title="src/pages/post-1.mdx"
+---
+titulo: Título da Minha Página
+---
+import { Image } from 'astro:assets';
+import foguete from '../assets/foguete.png';
# Minha Página MDX
-// Imagem local armazenada em src/imagens/foguete.svg
-
+// Imagem local armazenada em src/assets/
+
+
+
-// Imagem local armazenada em public/assets/estrelas.png
-
-
+// Imagens armazenada em public/imagens/
+
+
+
// Imagem remota em outro servidor
-
-
+
+
+
+
+```
+
+## Imagens em Coleções de Conteúdo
+
+Você pode declarar uma imagem associada para uma entrada de coleções de conteúdo, como a imagem de capa de uma postagem de blog, em seu frontmatter utilizando o caminho relativo a pasta atual:
+
+```md title="src/content/blog/minha-postagem.md" {3}
+---
+title: "Minha primeira postagem do blog"
+capa: "./capaprimeirapostagem.jpeg" # será resolvido como "src/content/blog/capaprimeirapostagem.jpeg"
+altCapa: "Uma fotografia de um pôr do sol atrás de uma cadeia de montanhas."
+---
+
+Essa é uma postagem no blog
+```
+
+O utilitário `image` para esquemas de coleções de conteúdo te permite validar os metadados da imagem utilizando Zod.
+
+```ts title="src/content/config.ts"
+import { defineCollection, z } from "astro:content";
+
+const blogCollection = defineCollection({
+ schema: ({ image }) => z.object({
+ titulo: z.string(),
+ capa: image().refine((img) => img.width >= 1080, {
+ mensagem: "Imagem de capa deve ter pelo menos 1080 pixels de largura!",
+ }),
+ altCapa: z.string(),
+ }),
+});
+
+export const collections = {
+ blog: blogCollection,
+};
+```
+
+A imagem será importada e transformada em metadados, te permitindo passá-la como o `src` para ``, ``, ou `getImage()`.
+
+O exemplo abaixo mostra a página de índice de um blog que renderiza a foto de capa e o título de cada postagem do blog do esquema acima:
+
+```astro title="src/pages/blog.astro" {10}
+---
+import { Image } from "astro:assets";
+import { getCollection } from "astro:content";
+const todasPostagensBlog = await getCollection("blog");
+---
+
+{
+ todasPostagensBlog.map((post) => (
+
+ ))
+}
+```
+
+## Imagens em componentes de frameworks de UI
+
+Ao adicionar imagens em um componente de framework de UI, utilize a sintaxe de imagem própria do framework para renderizar uma imagem (e.x. `` em JSX, `` em Svelte).
+
+Imagens locais devem **primeiro ser importadas** para acessar suas [propriedades de imagem](#imagens-locais-em-src) como `src`.
+
+```jsx title="src/components/ImagemReact.jsx"
+import estrelas from "../assets/estrelas.png"
+
+export default function ImagemReact() {
+ return (
+
+ )
+}
```
-### Em Componentes de Frameworks de UI
+```svelte title="src/components/ImagemSvelte.svelte"
+
+
+
-Ao adicionar imagens em um [componente de framework de UI](/pt-br/core-concepts/framework-components/) (e.x React, Svelte), utilize a sintaxe de imagem apropriada para aquele particular framework de componente.
+```
-## Aonde armazenar imagens
+#### Passando o componente Image
-### `src/`
+O componente ``, assim como qualquer outro componente Astro, **não está disponível para componentes de frameworks de UI**.
-Suas imagens armazenadas em `src/` podem ser utilizadas por componentes (`.astro`, `.mdx` e em outros frameworks de UI) mas não por arquivos Markdown.
+Porém, você pode passar o conteúdo estático gerado por `` para um componente de framework dentro de um arquivo `.astro` como um filho ou utilizando um [`` nomeado](/pt-br/core-concepts/framework-components/#posso-utilizar-componentes-astro-dentro-de-meus-componentes-de-frameworks):
-Nós recomendamos que você mantenha suas imagens em [`public/`](#public) ou as armazene [remotamente](#utilizando-imagens-de-um-cms-ou-cdn) se você precisa utilizar arquivos Markdown.
-Os importe de um **caminho de arquivo relativo** ou [atalho de importação](/pt-br/guides/aliases/) em qualquer arquivo de componente e então utilize a importação como o atributo `src` da imagem.
+```astro title="EnvolvedorImagem.astro"
+---
+import ComponenteReact from './ComponenteReact.jsx';
+import { Image } from "astro:assets"
+import estrelas from "~/estrelas/docline.png";
+---
+
+
+
+
+```
+## Gerando imagens com `getImage()`
+
+:::caution
+`getImage()` depende em APIs únicas do servidor e quebra a build quando é utilizado no cliente.
+:::
+
+A função `getImage()` foi planejada para gerar imagens destinadas a serem em outro lugar do que diretamente no HTML, por exemplo em uma [Rota de API](/pt-br/core-concepts/endpoints/#endpoints-do-servidor-rotas-de-api). Ela te permite criar seu próprio componente `` customizado.
+
+`getImage()` recebe um objeto de opções com as [mesmas propriedades que o componente Image](#propriedades) (exceto `alt`).
```astro
---
-// src/pages/index.astro
+import { getImage } from "astro:assets";
+import meuPlanoFundo from "../planoFundo.png"
-// Acesse imagens em `src/imagens/`
-import logo from '../imagens/logo.png';
+const planoFundoOtimizado = await getImage({src: meuPlanoFundo, format: 'avif'})
---
-
+
+
+```
+
+Retorna um objeto com as seguintes propriedades:
+
+```js
+{
+ options: {...} // Parâmetros originais passados
+ src: "https//..." // Caminho para a imagem gerada
+ attributes: {...} // Atributos HTML adicionais necessários para renderizar a imagem (width, height, style, etc..)
+}
```
-### `public/`
+## Texto Alternativo
-Suas imagens armazenadas em `public/` podem ser utilizadas por componentes (`.astro`, `.mdx` e outros frameworks de UI) e também por arquivos Markdown.
+Nem todos os usuários podem ver imagens da mesma forma, então acessibilidade é uma preocupação especialmente importante ao utilizar imagens. Utilize o atributo `alt` para fornecer [texto alternativo descritivo](https://www.w3.org/WAI/tutorials/images/) para imagens.
+Esse atributo é necessário para o componente ``. `` irá lançar um erro se nenhum texto alternativo for fornecido.
-Porém, arquivos no diretório `/public` são sempre servidas ou copiadas como estão, sem nenhum processamento. Se você está utilizando imagens fora de arquivos Markdown, nós recomendamos que imagens locais sejam mantidas em `src/` quando possível para que o Astro possa transformar, otimizar e fazer bundle delas.
+Se a imagem for meramente decorativa (ou seja, não contribui para o entendimento da página), defina `alt=""` para que leitores de tela saibam ignorar a imagem.
-O atributo `src` é **relativo ao diretório public**. No Markdown, você pode também utilizar a notação `![]()`.
+## Serviço de imagem padrão
-```astro title="src/pages/index.astro"
+[Sharp](https://github.com/lovell/sharp) é o serviço de imagem padrão utilizado em `astro:assets`.
+
+Se você preferir utilizar [Squoosh](https://github.com/GoogleChromeLabs/squoosh) para transformar suas imagens, atualize sua configuração com o seguinte:
+
+```js title="astro.config.mjs" ins={4-6}
+import { defineConfig, squooshImageService } from 'astro/config';
+
+export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+});
+```
+
+## Integrações da Comunidade
+
+Há diversas [integrações de imagem da comunidade](https://astro.build/integrations?search=images) por terceiros para otimizar e trabalhar com imagens em seu projeto Astro.
+
+## Atualize para v3.0 da v2.x
+
+`astro:assets` não está mais atrás de uma flag experimental no Astro v3.0.
+
+`` agora é um componente integrado e a integração `@astrojs/image` anterior foi removida.
+
+Essa e outras mudanças em como utilizar imagens no Astro pode causar algumas mudanças radicais ao atualizar seu projeto Astro de uma versão anterior.
+
+Por favor siga as instruções abaixo apropriadamente para atualizar um projeto Astro v2.x para v3.0.
+
+### Atualize de `experimental.assets`
+
+Se você anteriormente habilitou a flag experimental para `astro:assets`, você vai precisar atualizar seu projeto para Astro v3.0 que agora inclui funcionalidades de assets por padrão.
+
+#### Remova a flag `experimental.assets`
+
+Remova a flag experimental:
+
+```js title="astro.config.mjs" del={4-6}
+import { defineConfig } from 'astro/config';
+
+export default defineConfig({
+ experimental: {
+ assets: true
+ }
+});
+```
+
+Se necessário, também atualize seu arquivo `src/env.d.ts` para substituir a referência `astro/client-image` com `astro/client`:
+
+```ts title="src/env.d.ts" del={1} ins={2}
+///
+///
+```
+
+#### Remova o atalho de importação `~/assets`
+
+Esse atalho de importação não é mais incluso por padrão com `astro:assets`. Se você esteve utilizando esse atalho com assets experimentais, você deve convertê-los para camianhos de arquivo relativos, ou [criar seu próprio atalho de importação](/pt-br/guides/aliases/).
+
+```astro title="src/pages/posts/post-1.astro" del={2} ins={3}
---
-// Acesse imagens in `public/imagens/`
+import foguete from '~/assets/foguete.png'
+import foguete from '../../assets/foguete.png';
---
-
```
-### `src/assets/` (experimental)
+#### Adicione suporte simples de assets para Cloudflare, Deno, Vercel Edge e Netlify Edge
-Veja o guia [Assets (Experimental)](/pt-br/guides/assets/) para habilitar o uso experimental da pasta `/assets/`.
+Astro v3.0 permite `astro:assets` funcionar sem erros em Cloudflare, Deno, Vercel Edge e Netlify Edge, que não suporta a otimização integrada do Astro, Squoosh e Sharp. Note que Astro não realiza nenhuma transformação e processamento de imagem nesses ambientes. Porém, você ainda pode aproveitar os outros benefícios de se utilizar `astro:assets`, incluindo nenhum Cumulative Layout Shift (CLS), a aplicação do atributo `alt`, e a experiência de autoria consistente.
-Isso vai exigir que você atualize suas imagens existentes, remover a atual integração Image do Astro, e também vai exigir mudanças manuais adicionais para explorar as vantagens de algumas de suas funcionalidades.
+Se você anteriormente evitou utilizar `astro:assets` por conta dessas limitações, agora você pode utilizá-lo sem problemas. Você pode configurar o serviço de imagem no-op para explicitamente optar por esse compartamento:
-## Integração Image do Astro
+```js title="astro.config.mjs" ins={4-8}
+import { defineConfig } from 'astro/config';
-:::note[a ser depreciada em v3.0]
-A integração [`@astrojs/image`](https://github.com/withastro/astro/tree/main/packages/integrations/image) não terá mais suporte ativo no Astro v3.0.
+export default defineConfig({
+ image: {
+ service: {
+ entrypoint: 'astro/assets/services/noop'
+ }
+ }
+});
+```
-Nós sugerimos remover ela assim que for conveniente e utilizar o módulo experimental `astro:assets` que fará parte do `astro@3.0`.
+### Decida onde armazenar suas imagens
-Siga o [Guia de Assets (Experimental)](/pt-br/guides/assets/) para começar a usar a nova solução de imagens do Astro hoje mesmo!
+Veja o guia de Imagens para te ajudar a decidir [onde armazenar suas imagens](#onde-armazenar-imagens). Você pode desejar se aproveitar de novas opções para armazenar suas imagens com a flexibilidade adicional que `astro:assets` traz. Por exemplo, imagens relativas a partir do `src/` do seu projeto podem ser referenciadas em Markdown, MDX e Markdoc utilizando a sintaxe padrão do Markdown ``.
-**`astro:assets` não é um substituto completo do `@astrojs/image` nesse momento, mas está sob constante desenvolvimento.**
-:::
+### Atualize tags `` existentes
-Para documentação de como usar `@astrojs/image` no Astro v2, por favor veja a [documentação do pacote `@astrojs/image`](https://github.com/withastro/astro/blob/main/packages/integrations/image/README.md)
+Anteriormente, importar uma imagem iria retornar uma simples `string` com o caminho da imagem. Agora, assets de imagem importadas correspodem a seguinte assinatura:
-## Utilizando Imagens de um CMS ou CDN
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
-CDNs de imagens funcionam com Astro. Utilize a URL completa de uma imagem como o atributo `src` em uma tag `` ou notação do Markdown.
+Você deve atualizar o atributo `src` de quaisquer tags `` existentes (incluindo quaisquer [imagens em componentes de framework de UI](#imagens-em-componentes-de-frameworks-de-ui)) e você também pode atualizar outros atributos que agora estão disponíveis para você da imagem importada.
-Alternativamente, se o CDN providencia um SDK Node.js, você pode utilizá-lo no seu projeto. Por exemplo, o [SDK da Cloudinary](https://cloudinary.com/documentation/node_integration) podem gerar a tag `` com a `src` apropriada para você.
+```astro title="src/components/MeuComponente.astro" ".src" ".width" ".height" del={4} ins={6}
+---
+import foguete from '../imagens/foguete.svg';
+---
+
-## Texto Alternativo
+
+```
-Nem todos os usuários podem ver imagens da mesma forma, então acessibilidade é uma preocupação especialmente importante ao se utilizar imagens. Use o atributo `alt` para providenciar [texto alternativo descritivo](https://www.w3.org/WAI/tutorials/images/) para imagens.
+### Atualize seus arquivos Markdown, MDX e Markdoc
-Esse atributo é necessário para que os componentes `` e `` da integração Image. Esses componentes irão jogar com um erro quando nenhum texto alternativo é providenciado.
+Imagens relativas da `src/` do seu projeto agora podem ser referenciadas em Markdown, MDX e Markdoc utilizando a sintaxe padrão do Markdown ``.
-Se a imagem é meramente decorativa (ou seja, não contribui para o entendimento da página), defina `alt=""` para que a imagem seja propriamente entendida e ignorada por leitores de tela.
+Isso te permite mover suas imagens do diretório `public/` para o `src/` do seu projeto onde agora elas serão processadas e otimizadas. Suas imagens existentes em `public/` e imagens remotas ainda são válidas mas não são otimizadas pelo processo de build do Astro.
+```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/"
+# Minha Página Markdown
+
+
-## Integrações da Comunidade
+
+
+```
+
+Se você requer mais controle sobre seus atributos de imagem, nós recomendamos utilizar o formato de arquivo `.mdx`, que te permite incluir o componente `` do Astro ou uma tag `` JSX em adição a sintaxe do Markdown. Utilize a [integração MDX](/pt-br/guides/integrations-guide/mdx/) para adicionar suporte de MDX para Astro.
+
+### Remova `@astrojs/image`
+
+
+Se você estava utilizando a integração de imagem em Astro v2.x, complete as seguintes etapas:
+
+1. Remova a integração `@astrojs/image`.
+
+ Você deve [remover a integração](/pt-br/guides/integrations-guide/#removendo-uma-integração) a desinstalando e então a removendo do seu arquivo `astro.config.mjs`.
+
+ ```js del={3,7}
+ // astro.config.mjs
+ import { defineConfig } from 'astro/config';
+ import image from '@astrojs/image';
+
+ export default defineConfig({
+ integrations: [
+ image(),
+ ]
+ })
+ ```
+
+2. Migre quaisquer componentes ``.
+
+ Modifique todas as declarações `import` de `@astrojs/image/components` para `astro:assets` para utilizar o novo componente `` integrado.
+
+ Remova quaisquer atributos do componente que não são [propriedades de asset de imagem atualmente suportadas](#propriedades).
+
+ Por exemplo, `aspectRatio` não é mais suportado, já que agora é automaticamente inferido dos atributos `width` e `height`.
+
+ ```astro title="src/components/MeuComponente.astro" del= {2,11} ins={3}
+ ---
+ import { Image } from '@astrojs/image/components';
+ import { Image } from 'astro:assets'
+ import imagemLocal from "../assets/logo.png";
+ const altLocal = "A logo do Astro";
+ ---
+
+
+ ```
+
+3. Remova quaisquer componentes ``.
+
+ Atualmente, a funcionalidade de assets integrada não inclui um componente ``.
+
+ No lugar, você pode utilizar os atributos de imagem HTML `srcset` e `sizes` ou a tag `` [para direção de imagem ou para criar imagens responsivas](https://developer.mozilla.org/pt-BR/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction).
+
+4. Escolha o serviço de imagem padrão.
+
+ [Sharp](https://github.com/lovell/sharp) agora é o serviço de imagem padrão usado para `astro:assets`. Se você quiser utilizar Sharp, nenhuma configuração é necessária.
+
+ Se você preferir utilizar [Squoosh](https://github.com/GoogleChromeLabs/squoosh) para transformar suas imagens, atualize sua configuração com a opção `image.service` a seguir:
+
+ ```js title="astro.config.mjs" ins={4-6}
+ import { defineConfig, squooshImageService } from 'astro/config';
+
+ export default defineConfig({
+ image: {
+ service: squooshImageService(),
+ },
+ });
+ ```
+
+### Atualize Esquemas de Coleções de Conteúdo
+
+Agora você pode declarar uma imagem associada a uma entrada de coleções de conteúdo, como a imagem de capa de uma postagem de blog, em seu frontmatter utilizando seu caminho relativo a pasta atual.
-Em adição a integração oficial [`@astrojs/image`](/pt-br/guides/integrations-guide/image/), tem várias [integrações de imagens da comunidade](https://astro.build/integrations?search=images) feitas por terceiros para otimizar e trabalhar com imagens em seu projeto Astro.
+O novo utilitário `image` para coleções de conteúdo te permite validar os metadados da imagem utilizando Zod. Aprenda mais sobre [como utilizar imagens em coleções de conteúdo](/pt-br/guides/images/#imagens-em-coleções-de-conteúdo)
\ No newline at end of file
diff --git a/src/content/docs/pt-br/guides/integrations-guide.mdx b/src/content/docs/pt-br/guides/integrations-guide.mdx
index bc1dc1933f289..8b9e3c79b15c8 100644
--- a/src/content/docs/pt-br/guides/integrations-guide.mdx
+++ b/src/content/docs/pt-br/guides/integrations-guide.mdx
@@ -126,17 +126,17 @@ Para remover uma integração, primeiro desinstale a integração do seu projeto
```shell
- npm uninstall @astrojs/image
+ npm uninstall @astrojs/react
```
```shell
- pnpm uninstall @astrojs/image
+ pnpm uninstall @astrojs/react
```
```shell
- yarn remove @astrojs/image
+ yarn remove @astrojs/react
```
@@ -146,11 +146,11 @@ Depois, remova a integração do seu arquivo `astro.config.*`:
```js title="astro.config.mjs" del={3,7}
import { defineConfig } from 'astro/config'
-import image from "@astrojs/image";
+import react from "@astrojs/react";
export default defineConfig({
integrations: [
- image()
+ react()
]
})
```
diff --git a/src/content/docs/pt-br/guides/markdown-content.mdx b/src/content/docs/pt-br/guides/markdown-content.mdx
index 6c41fa67c052f..2e9ed87ff8e20 100644
--- a/src/content/docs/pt-br/guides/markdown-content.mdx
+++ b/src/content/docs/pt-br/guides/markdown-content.mdx
@@ -58,65 +58,6 @@ Provavelmente não está muito estiloso, porém o Markdown suporta:
📚 Leia mais sobre o [roteamento baseado em arquivos](/pt-br/core-concepts/routing/) do Astro ou opções para criar [rotas dinâmicas](/pt-br/core-concepts/routing/#rotas-dinâmicas).
-### Páginas de Rascunho
-
-`draft: true` é um valor opcional de frontmatter irá marcar uma individual página ou postagem Markdown ou MDX como "não publicada". Por padrão, essa página será:
-
-- excluída da build do site (a página não será construída)
-
-- retornada por `Astro.glob()` (visível na lista de postagens)
-
-```markdown {5}
----
-# src/pages/post/postagem-blog.md
-layout: ../../layouts/LayoutBase.astro
-title: Minha Postagem do Blog
-draft: true
----
-
-Esta é a postagem que eu estou fazendo no meu blog.
-
-Nenhuma página terá build feito para esta postagem.
-
-Para fazer a build e publicar esta postagem:
-
-- atualize o frontmatter para `draft: false` ou
-- remova a propriedade `draft` completamente.
-
-Porém, esta página _será_ retornada por quaisquer requisições `Astro.glob()` correspondentes.
-```
-
-Para excluir postagens de rascunho de serem inclusas no arquivo de postagens, ou listar as postagens mais recentes, você pode filtrar os resultados retornados pelo `Astro.glob()`:
-
-```js
-const postagens = await Astro.glob('../pages/postagens/*.md');
-const postagensSemRascunhos = postagens.filter((postagem) => !postagem.frontmatter.draft);
-```
-
-:::note[Usando coleções de conteúdo?]
-Essa funcionalidade não suporta coleções de conteúdo, entretanto você pode utilizar um [filtro de consulta de coleção](/pt-br/guides/content-collections/#filtrando-consultas-de-coleção) para filtrar seus rascunhos de postagens.
-:::
-
-#### Habilitando a build de páginas de rascunho
-
-Para habilitar a build de páginas de rascunho por padrão, atualize `astro.config.mjs` adicionando `drafts: true` em `markdown` ou na integração `mdx`:
-
-```js title="astro.config.mjs" ins={5, 8}
-import { defineConfig } from 'astro/config';
-
-export default defineConfig({
- markdown: {
- drafts: true,
- },
- integrations: [mdx({
- drafts: true,
- })],
-});
-```
-
-:::tip
-Você também pode passar a flag `--drafts` ao executar `astro build` para fazer a build de páginas de rascunho!
-:::
## Funcionalidades do Markdown
@@ -186,7 +127,7 @@ Por exemplo, para prevenir `<` de ser interpretado como o começo de um elemento
Adicionar a [integração MDX](/pt-br/guides/integrations-guide/mdx/) do Astro aprimora sua experiência de autoria com Markdown com variáveis JSX, expressões e componentes.
-Ela também adiciona funcionalidades extras ao MDX padrão, incluindo suporte para [frontmatter estilo Markdown no MDX](https://mdxjs.com/guides/frontmatter/). Isso te permite utilizar a maioria das funcionalidades integradas para Markdown do Astro como a propriedade [frontmatter `layout`](#frontmatter-layout) e a configuração de [páginas de rascunho](#páginas-de-rascunho).
+Ela também adiciona funcionalidades extras ao MDX padrão, incluindo suporte para [frontmatter estilo Markdown no MDX](https://mdxjs.com/guides/frontmatter/). Isso te permite utilizar a maioria das funcionalidades integradas para Markdown do Astro como a propriedade [frontmatter `layout`](#frontmatter-layout).
Arquivos `.mdx` devem ser escritos na [sintaxe do MDX](https://mdxjs.com/docs/what-is-mdx/#mdx-syntax) ao invés da sintaxe semelhante ao HTML do Astro.
diff --git a/src/content/docs/pt-br/guides/middleware.mdx b/src/content/docs/pt-br/guides/middleware.mdx
index 22e7b53b9d53c..a9e270525b193 100644
--- a/src/content/docs/pt-br/guides/middleware.mdx
+++ b/src/content/docs/pt-br/guides/middleware.mdx
@@ -45,7 +45,7 @@ Você pode importar e utilizar a função utilitária `defineMiddleware()` para
```ts
// src/middleware.ts
-import { defineMiddleware } from "astro/middleware";
+import { defineMiddleware } from "astro:middleware";
// `context` e `next` são tipados automaticamente
export const onRequest = defineMiddleware((context, next) => {
@@ -138,7 +138,7 @@ export const onRequest = async (context, next) => {
Múltiplos middlewares podem ser conectados em uma sequência ordenada utilizando [`sequence()`](#sequence):
```js title="src/middleware.js"
-import { sequence } from "astro/middleware";
+import { sequence } from "astro:middleware";
async function validacao(_, next) {
console.log("validação da requisição");
diff --git a/src/content/docs/pt-br/guides/rss.mdx b/src/content/docs/pt-br/guides/rss.mdx
index 9afe081bf01cf..ce36f06d90e81 100644
--- a/src/content/docs/pt-br/guides/rss.mdx
+++ b/src/content/docs/pt-br/guides/rss.mdx
@@ -47,7 +47,7 @@ O arquivo de exemplo abaixo `src/pages/rss.xml.js` vai criar um feed RSS em `sit
```js title="src/pages/rss.xml.js"
import rss from '@astrojs/rss';
-export function get(context) {
+export function GET(context) {
return rss({
// campo `` no xml final
title: 'Blog do Buzz',
@@ -81,7 +81,7 @@ Para criar um feed RSS de páginas gerenciadas em [coleções de conteúdo](/pt-
import rss from '@astrojs/rss';
import { getCollection } from 'astro:content';
-export async function get(context) {
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Blog do Buzz',
@@ -128,7 +128,7 @@ Essa função assume, mas não verifica, que todas as propriedades necessárias
```js title="src/pages/rss.xml.js" "pagesGlobToRssItems" "await pagesGlobToRssItems("
import rss, { pagesGlobToRssItems } from '@astrojs/rss';
-export async function get(context) {
+export async function GET(context) {
return rss({
title: 'Blog do Buzz',
description: 'O guia de um humilde Astronauta para as estrelas',
@@ -166,7 +166,7 @@ import sanitizeHtml from 'sanitize-html';
import MarkdownIt from 'markdown-it';
const parser = new MarkdownIt();
-export async function get(context) {
+export async function GET(context) {
const blog = await getCollection('blog');
return rss({
title: 'Blog do Buzz',
@@ -188,7 +188,7 @@ Ao utilizar importações de glob com Markdown, você pode utilizar o utilitári
import rss from '@astrojs/rss';
import sanitizeHtml from 'sanitize-html';
-export function get(context) {
+export function GET(context) {
const resultadoImportacaoPostagem = import.meta.glob('../postagens/**/*.md', { eager: true });
const postagens = Object.values(resultadoImportacaoPostagem);
return rss({
diff --git a/src/content/docs/pt-br/guides/server-side-rendering.mdx b/src/content/docs/pt-br/guides/server-side-rendering.mdx
index c9248e622d11e..cd9f64b4651a6 100644
--- a/src/content/docs/pt-br/guides/server-side-rendering.mdx
+++ b/src/content/docs/pt-br/guides/server-side-rendering.mdx
@@ -172,7 +172,7 @@ E para um endpoint:
```js title="src/pages/meuendpoint.js" {1}
export const prerender = true;
-export async function get() {
+export async function GET() {
return {
body: JSON.stringify({ message: `Este é meu endpoint estático` }),
};
@@ -186,7 +186,7 @@ Para um aplicação majoritariamente estática configurada como `output: hybrid`
```js title="src/pages/numeroaleatorio.js" {1}
export const prerender = false;
-export async function get() {
+export async function GET() {
let numero = Math.random();
return {
body: JSON.stringify({ numero, mensagem: `Aqui está um número aleatório: ${numero}` }),
diff --git a/src/content/docs/pt-br/guides/styling.mdx b/src/content/docs/pt-br/guides/styling.mdx
index 6f2764d526e56..979ef61efedea 100644
--- a/src/content/docs/pt-br/guides/styling.mdx
+++ b/src/content/docs/pt-br/guides/styling.mdx
@@ -41,11 +41,11 @@ Este CSS:
Compila para isto:
```astro
@@ -159,7 +159,7 @@ import MeuComponente from "../components/MeuComponente.astro"
Isso será vermelho!
```
-Esse padrão te permite estilizar componentes filhos diretamente. Astro irá passar o nome de classe com escopo do pai (e.x. `astro-HHNQFKH6`) através da prop `class` automaticamente, incluindo o filho no seu escopo de pai.
+Esse padrão te permite estilizar componentes filhos diretamente. Astro irá passar o nome de classe com escopo do pai (e.x. `astro-hhnqfkh6`) através da prop `class` automaticamente, incluindo o filho no seu escopo de pai. Note que esse padrão funciona apenas quando sua [opção `scopedStyleStrategy`](/pt-br/reference/configuration-reference/#scopedstylestrategy) é `'where'` ou `'class'`.
:::note[Classes com escopo de componentes pai]
Por conta da prop `class` incluir o filho no escopo do seu pai, é possível que estilos cascatem do pai para o filho. Para evitar que isso tenha efeitos colaterais indesejados, certifique-se de utilizar nomes de classe únicos no componente filho.
@@ -529,26 +529,38 @@ Se você estiver utilizando Tailwind, o [plugin typography](https://tailwindcss.
## Produção
-### Controle de pacote
+### Controle de bundle
-Quando o Astro faz a build do seu site para lançamento em produção, ele combina seu CSS em pedaços. Cada página no seu site é seu próprio pedaço, e adicionalmente, o CSS que é compartilhado entre múltiplas páginas é dividido em seus próprios pedaços para reutilização.
+Quando o Astro faz a build do seu site para lançamento em produção, ele minifica e combina seu CSS em pedaços. Cada página no seu site ganha seu próprio pedaço, e adicionalmente, o CSS que é compartilhado entre múltiplas páginas é dividido em seus próprios pedaços para reutilização.
-Em cada um dos seus arquivos HTML vai ter tags `` adicionadas, uma para cada pedaço que a página precisa.
+Contudo, quando você tem diversas páginas compartilhando estilos, alguns pedaços compartilhados podem se tornar realmente pequenos. Se todos eles fossem enviados separadamente, isso levaria a muitas requisições de folhas de estilo e afetaria a performance do site. Portanto, por padrão o Astro irá fazer link apenas daquelas no seu HTML acima de 4kB em tamanho como tags ``, enquanto adiciona inline as menores como `
+```
+
+### Removido: Planificação automática do valor de retorno de `getStaticPaths()`
+
+No Astro v2.x, o valor de retorno de [`getStaticPaths()`](/pt-br/reference/api-reference/#getstaticpaths) era automaticamente planificado para te permitir retornar um array sem nenhum erro.
+
+Astro v3.0 remove a planificação automática do resultado de `getStaticPaths()`.
+
+#### O que devo fazer?
+
+Se você está retornando um array de arrays no lugar de um array de _objetos_ (como é esperado), `.flatMap` e `.flat` agora devem ser usados para garantir que você está retornando um array plano.
+
+Uma [mensagem de erro indicando que o valor de retorno de `getStaticPath()` deve ser um array de objetos](/pt-br/reference/errors/invalid-get-static-paths-entry/#what-went-wrong) será providenciado se você precisa atualizar seu código.
+
+### Movido: `astro check` agora requer um pacote externo
+
+No Astro v2.x, [`astro check`](/pt-br/reference/cli-reference/#astro-check) era incluso com o Astro por padrão, e suas dependências eram embutidas no Astro. Isso significava em um pacote maior, independente se você usava ou não `astro check`. Isso também te prevenia de ter controle sobre a versão do TypeScript e o Servidor de Linguagem do Astro a se utilizar.
+
+
+Astro v3.0 move o comando `astro check` para fora do núcleo do Astro e agora requer o pacote externo `@astrojs/check`. Adicionalmente, você deve instalar `typescript` em seu projeto para utilizar o comando `astro check`.
+
+#### O que devo fazer?
+
+Execute o comando `astro check` após atualizar para o Astro v3.0 e siga as instruções para instalar as dependências necessárias, ou manualmente instale `@astrojs/check` e `typescript` em seu projeto.
+
+### Depreciado: `build.excludeMiddleware` e `build.split`
+
+No Astro v2.x, `build.excludeMiddleware` e `build.split` eram utilizados para mudar como arquivos específicos eram emitidos ao utilizar um adaptador no modo SSR.
+
+Astro v3.0 substitui essas opções de configuração da build com novas [opções de configuração de adaptadores SSR](/pt-br/guides/integrations-guide/#integrações-oficiais) para realizar as mesmas tarefas: `edgeMiddleware` e `functionPerRoute`.
+
+#### O que devo fazer?
+
+Atualize o arquivo de configuração do Astro para agora utilizar as novas opções **na configuração do adaptador** diretamente.
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import vercel from "@astrojs/vercel/serverless";
+
+export default defineConfig({
+ build: {
+ excludeMiddleware: true
+ },
+ adapter: vercel({
+ edgeMiddleware: true
+ }),
+});
+```
+
+```js title="astro.config.mjs" del={5-7} ins={9}
+import { defineConfig } from "astro/config";
+import netlify from "@astrojs/netlify/functions";
+
+export default defineConfig({
+ build: {
+ split: true
+ },
+ adapter: netlify({
+ functionPerRoute: true
+ }),
+});
+```
+
+### Depreciado: `markdown.drafts`
+
+No Astro v2.x, a configuração `markdown.drafts` te permitia ter páginas de rascunho que eram disponibilizadas ao executar o servidor de desenvolvimento, mas não na build para produção.
+
+Astro v3.0 deprecia essa funcionalidade em favor do método de coleções de conteúdo de manipular páginas de rascunho filtrando manualmente no lugar, o que te dá mais controle sobre a funcionalidade.
+
+#### O que devo fazer?
+
+Para continuar a marcar algumas páginas em seu projeto como rascunhos, [migue para coleções de conteúdo](/pt-br/guides/content-collections/#migrando-do-roteamento-baseado-em-arquivos) e [filtre páginas manualmente](/pt-br/guides/content-collections/#filtrando-consultas-de-coleção) com a propriedade do frontmatter `draft: true` no lugar.
+
+### Depreciado: retornar um objeto simples de endpoints
+
+No Astro v2.x, endpoints podiam retornar um objeto simples, que seria convertido para uma resposta JSON.
+
+Astro v3.0 deprecia esse comportamento em favor de retornar um objeto `Response` diretamente.
+
+#### O que devo fazer?
+
+Atualize seus endpoints para reotrnar um objeto `Response` diretamente.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "titulo": "Blog do Bob" }};
+ return new Response(JSON.stringify({ "titulo": "Blog do Bob" }));
+}
+```
+
+Se você realmente precisar manter o formato anterior, você pode utilizar o objeto `ResponseWithEncoding`, mas isso será depreciado no futuro.
+
+```ts title="endpoint.json.ts" del={2} ins={3}
+export async function GET() {
+ return { body: { "titulo": "Blog do Bob" } };
+ return new ResponseWithEncoding({ body: { "titulo": "Blog do Bob" }});
+}
+```
+
+
+### Padrão modificado: porta `3000`
+
+No Astro v2.x, Astro era executado na porta `3000` por padrão.
+
+Astro v3.0 muda a [porta padrão](/pt-br/reference/cli-reference/#--port) para `4321`. 🚀
+
+#### O que devo fazer?
+
+Atualize quaisquer referências a `localhost:3000`, por exemplo em testes ou em seu `README`, para refletir a nova porta `localhost:4321`.
+
+
+### Padrão modificado: import.meta.env.BASE_URL `trailingSlash`
+
+No Astro v2.x, `import.meta.env.BASE_URL` anexava sua opção [`base`](/pt-br/reference/configuration-reference/#base) com [`trailingSlash`](/pt-br/reference/configuration-reference/#trailingslash) por padrão. `trailingSlash: "ignore"` também anexava com uma barra final.
+
+Astro v3.0 não mais anexa `import.meta.env.BASE_URL` com uma barra final por padrão, nem quando `trailingSlash: "ignore"` é definido. (O comportamento existente de `base` em combinação com `trailingSlash: "always"` ou `trailingSlash: "never"` não mudou.)
+
+#### O que devo fazer?
+
+Se sua `base` já tem uma barra final, nenhuma mudança é necessária.
+
+Se sua `base` não tem uma barra final, adicione uma se você deseja preservar o comportamento padrão anterior (ou `trailingSlash: "ignore"`):
+
+```js title="astro.config.mjs" del={4} ins={5}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ base: 'minha-base',
+ base: 'minha-base/',
+});
+```
+
+### Padrão modificado: `compressHTML`
+
+No Astro v2.x, Astro apenas comprimia seu HTML emitido quando [`compressHTML`](/pt-br/reference/configuration-reference/#compresshtml) era explicitamente definido como `true`. O valor padrão era `false`.
+
+Astro v3.0 agora comprime HTML emitido por padrão.
+
+#### O que devo fazer?
+
+Agora você pode remover `compressHTML: true` de sua configuração já que esse é o novo comportamento padrão.
+
+```js title="astro.config.mjs" del={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ compressHTML: true
+})
+```
+
+Agora você deve definir `compressHTML: false` para optar por sair da compressão de HTML.
+
+### Padrão modificado: `scopedStyleStrategy`
+
+No Astro v2.x, o valor padrão de [`scopedStyleStrategy`](/pt-br/reference/configuration-reference/#scopedstylestrategy) era `"where"`.
+
+Astro v3.0 introduz um novo valor padrão: `"attribute"`. Por padrão, estilos agora são aplicados utilizando atributos `data-*`.
+
+#### O que devo fazer?
+
+Para manter o [escopo dos estilos](/pt-br/guides/styling/#estilos-com-escopo), atualize o arquivo de configuração para o valor padrão anterior:
+
+
+```js title="astro.config.mjs" ins={4}
+import { defineConfig } from "astro/config";
+
+export default defineConfig({
+ scopedStyleStrategy: "where"
+})
+```
+
+### Padrão modificado: `inlineStyleSheets`
+
+No Astro v2.x, todas as folhas de estilo foram enviadas como tags link por padrão. Você poderia optar por adicioná-las inline em tags `
+```
+
+### ``
+
+[Astro 模板语法](/zh-cn/core-concepts/astro-syntax/) 也支持直接编写 `` 标签,完全控制其最终输出。这些图像不会被处理和优化。
+
+它接受所有 HTML `` 标签属性,唯一必需的属性是 `src`。
+
+#### `src/` 中的本地图像
+
+本地图像必须从现有的 `.astro` 文件的相对路径**导入**,或者配置并使用 [导入别名](/zh-cn/guides/aliases/)。然后,你可以访问图像的 `src` 和其他属性,以在 `` 标签中使用。
+
+例如,使用图像自己的 `height` 和 `width` 属性,以避免布局位移累计 CLS 并改善核心 Web 性能指标。
+
+```astro "myDog.width" "myDog.height"
+---
+// 导入本地图像
+import myDog from `../../images/pets/local-dog.jpg`
+---
+// 访问图像的属性
+
+```
+
+导入的图像资源与以下签名相匹配:
+
+```ts
+interface ImageMetadata {
+ src: string;
+ width: number;
+ height: number;
+ format: string;
+}
+```
+
+#### `public/` 中的图像
+对于位于 `public/` 中的图像,请使用图像相对于 public 文件夹的**文件路径**作为 `src` 值:
+
+```astro '"/images/public-cat.jpg"'
+
+```
-可以在 `.md` 文件中使用 Markdown 标准语法 `![]()`,或 HTML 标准语法 `` 标签,来调用位于 `public/` 文件夹下或其它服务器上的图片。
+#### 远程图像
+
+对于远程图像,请使用图像的**完整 URL**作为 `src` 值:
+
+```astro '"https://example.com/remote-cat.jpg"'
+
+```
+
+### 选择 `` 还是 ``
+
+`` 组件会优化图像,并根据原始宽高比推断宽度和高度(对于本地图像),以避免 CLS。但是,它只适用于某些格式,并且不提供 `` 元素,也不支持 `srcset`。
+
+当你不能使用 `` 组件时,请使用 HTML `` 元素,例如:
+ - 不支持的图像格式
+ - 当你不想让 Astro 优化你的图像时
+ - 为了在客户端动态访问和更改 `src` 属性
+
+### 授权远程图像
+
+你可以使用 [`image.domains`](/zh-cn/reference/configuration-reference/#imagedomains) 和 [`image.remotePatterns`](/zh-cn/reference/configuration-reference/#imageremotepatterns) 配置授权图像源 URL 域和模式列表,以进行图像优化。这个配置是一个额外的安全层,用于在显示来自外部源的图像时保护你的站点。
+
+来自其他来源的远程图像不会被优化,但是使用 `` 组件可以防止累积布局移位(CLS)。
+
+例如,以下配置将只允许来自 `astro.build` 的远程图像进行优化:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ domains: ["astro.build"],
+ }
+});
+```
+
+以下配置将只允许来自 HTTPS 主机的远程图像:
+
+```ts
+// astro.config.mjs
+export default defineConfig({
+ image: {
+ remotePatterns: [{ protocol: "https" }],
+ }
+});
+```
+
+## 使用 CMS 或 CDN 中的图像
+
+图像 CDN 与所有 Astro 图像选项兼容。在 `` 组件、`` 标签或 Markdown 表示法中,使用图像的完整 URL 作为 `src` 属性。对于远程图像的图像优化,还需要 [配置授权域或 URL 模式](#授权远程图像)。
+
+或者,如果 CDN 提供了 Node.js SDK,你可以在项目中使用它。例如,[Cloudinary 的 SDK](https://cloudinary.com/documentation/node_integration) 可以为你生成一个带有适当 `src` 的 `` 标签。
+
+## Markdown 文件中的图像
+
+在 `.md` 文件中使用标准的 Markdown `` 语法。这个语法可以与 Astro 的 [图像服务 API](/zh-cn/reference/image-service-reference/) 一起使用,来优化你的本地图像和授权的远程图像。
-如果你无法将图片保留在 `public/` 中,我们建议启用 [资源的实验性支持](/zh-cn/guides/assets/), 或使用 `.mdx` 文件格式,该格式允许你将导入的组件与类似 Markdown 的语法结合起来。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 向 Astro 添加对 MDX 的支持。
```md
# 我的 Markdown 页面
-
-
-
+
+
+
+
+
+
+
-
-
-
+
+
+
```
-### 在 MDX 文件中
+本地图像不支持 `` 标签,也不支持 `` 组件。
-你可以在 .mdx 文件中使用标准 Markdown `![]()` 语法或 JSX 的 `` 标签来显示 `public/ ` 文件夹或远程服务器中的图片。
+如果你需要对图像属性做更多的控制,我们建议使用 `.mdx` 文件格式,除了 Markdown 语法,你还可以使用 Astro 的 `` 组件或 JSX `` 标签。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 为 Astro 添加对 MDX 的支持。
-此外,你也可以导入和使用位于项目 `src/` 目录中的图像,就像在 Astro 组件中一样。
+## MDX 文件中的图像
+你可以通过导入组件和图像在你的 `.mdx` 文件中使用 Astro 的 `` 组件 和 JSX `` 标签。使用它们就像 [在 `.astro` 文件中使用](#astro-文件中的图像) 一样。
+
+此外,还支持 [标准的 Markdown `` 语法](#markdown-文件中的图像),无需导入。
```mdx title="src/pages/post-1.mdx"
+---
+title: 我的页面标题
+---
+import { Image } from 'astro:assets';
+import rocket from '../assets/rocket.png';
-import rocket from '../images/rocket.svg';
+# 我的 MDX 页面
-# My MDX Page
+// 存储在 src/assets/ 中的本地图像
+
+
+
-// 存放在项目中 src/images/rocket.svg 路径的图片
-
+// 存储在 public/images/ 中的图像
+
+
+
-// 存放在项目中 public/assets/stars.png 路径的图片
-
-
+// 其它服务上的远程图像
+
+
+
-// 位于其它服务器上的图片
-
-
```
-### UI 框架中的组件
+## 内容集合中的图像
-当在 [UI 框架组件](/zh-cn/core-concepts/framework-components/)(例如 React、Svelte)中添加图像时,请使用适合该框架的图像语法。
+你可以在 frontmatter 中声明一个与内容集合条目相关联的图像,例如博客文章的封面图像,使用相对于当前文件夹的路径:
+```md title="src/content/blog/my-post.md" {3}
+---
+title: "我的第一篇博客文章"
+cover: "./firstpostcover.jpeg" # 将解析为 "src/content/blog/firstblogcover.jpeg"
+coverAlt: "一张山脉后面的日落照片。"
+---
+这是一篇博客文章。
+```
-## 存放图片的位置
+内容集合 schema 中的 `image` 助手允许你使用 Zod 验证图像元数据。
-### `src/`
+```ts title="src/content/config.ts"
+import { defineCollection, z } from "astro:content";
-存储在 `src/`中的图像可以由组件(`.astro`,`.mdx`和其他 UI 框架)使用,但不能在 Markdown 文档中使用。
+const blogCollection = defineCollection({
+ schema: ({ image }) => z.object({
+ title: z.string(),
+ cover: image().refine((img) => img.width >= 1080, {
+ message: "封面图片必须至少1080像素宽!",
+ }),
+ coverAlt: z.string(),
+ }),
+});
-如果您必须使用 Markdown 文档,我们建议你将图像保存在 ['public/'](#public) 中或 [远程](#使用-cms-或-cdn-上的图片) 存储他们。
+export const collections = {
+ blog: blogCollection,
+};
+```
-从任何组件文档中的 **相对文档路径** 或 [导入别名](/zh-cn/guides/aliases/) 导入它们,然后像使用 `src`属性一样使用。
+图像将被导入并转换为元数据,允许你将其作为 `src` 传递给 ``、`` 或 `getImage()`。
-```astro
+下面的示例显示了一个博客索引页面,该页面从上面的模式中呈现了每篇博客文章的封面照片和标题:
+
+```astro title="src/pages/blog.astro" {10}
---
-// src/pages/index.astro
+import { Image } from "astro:assets";
+import { getCollection } from "astro:content";
+const allBlogPosts = await getCollection("blog");
+---
+
+{
+ allBlogPosts.map((post) => (
+