From 535de92bbfad35724d28209f8b360d70f69fb0cd Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 11 Jul 2023 19:29:02 +0000 Subject: [PATCH 01/58] starting to take notes --- src/content/docs/en/guides/assets.mdx | 85 ++++++++++++++++++++++++++- 1 file changed, 82 insertions(+), 3 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index ef008023c2364..796df73139d0a 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -14,9 +14,88 @@ The new assets experience currently features: - Integration with content collections - Improved error messages and types -:::caution -Assets are an experimental Astro feature introduced in v2.1. This API is subject to change before it is marked as stable. -::: +## New stuff + +## Images in Markdown + +- in `.md` files, you must only use the `![]()` syntax to display images. +- You cannot use a `` element directly, nor the Astro `` component +- the images can be: + - remote images, using a full URL e.g. `![](https://example.com/images/remote-image.png)` + - images stored in `public/`, using the URL path relative to the public directory e.g. `![](/assets/images/my-public-image.jpg)` for `public/assets/images/my-public-image.jpg` + - local images in `src/`, using a relative path to the image from the file you're currently in + - if located in `src/assets/` you can use the `~/assets/my-image.png` alias + - if co-located in the same folder as your `.md` file, use `./my-image.png` + - otherwise, use a location path relative to your `.md` file: + e.g. `src/content/docs/v1/introduction.md`'s relative path to `src/images/my-image.png` is `../../../images/my-image.png` + +### Images in UI framework components + +- Use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte, etc.) +- must import local images, and import still takes the shape mentioned above, so e.g. `src={myImage.src} width={myImage.width}` + +```jsx title="src/components/ReactImg.jsx" +import docline from "../assets/docline.png" + +export default function ReactImg () { + + return ( + A cartoon about docs. + ) +} +``` + +```svelte title="src/components/SvelteImg.svelte" + + +A cartoon about docs. +``` + +- can NOT use Astro's `` component because that's an ASTRO component, and you can't use Astro inside other framework components +- But, you can use the Astro slot pattern to pass static content generated by Astro components as children inside an Astro component: + + +```astro title="ImageSlots.astro" +--- +import ReactComponent from './ReactComponent.jsx'; +import { Image } from "astro:assets" +import docline from "~/assets/docline.png"; +import SvelteImg from './SvelteImg.svelte'; +--- + + +

Using Astro's Image component

+ text +

Using a Svelte Image component

+ +
+``` + +```jsx title="ReactComponent.jsx" +export default function ReactComponent ({children}) { + return ( + <> +

Some image tests

+
{children}
+ + ) +} +``` + +```astro title="MyAstroPage.astro" +--- +import ImageSlots from '../components/ImageSlots.astro'; +import Layout from '../layouts/BlogPost.astro'; +--- + + + + +``` + + ## Enabling Assets in your Project From 3ff1e78d56ac85110d024dfa276722851cf1dab2 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 12 Jul 2023 13:40:29 +0000 Subject: [PATCH 02/58] notes re: using in Astro files --- src/content/docs/en/guides/assets.mdx | 67 ++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 11 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 796df73139d0a..91978a812fd7d 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -14,7 +14,36 @@ The new assets experience currently features: - Integration with content collections - Improved error messages and types -## New stuff +## New stuff - rough notes + +## Images in `.astro` files + +- **local images** must be imported either using the built-in alias for the `/assets/` folder: `import cat from '~/assets/funny/threads.jpg';` or the relative path from the existing astro page: `../assets/funny/threads.jpg` Required for both HTML `` and Astro ``. +- `` also requires importing the Image component from the `astro:assets` module: `import { Image } from 'astro:assets'` + +- **remote images** are not imported; use their full URL as the `src` property. When using the `` component, you must specify both `width` and `height` in addition to the always-required `alt`: `a chickadee sitting on a branch with fluff in its beak` + +- **images in public** are not imported; use their path relative to your public folder as the `src` property, both for the HTML `` tag and for the Astro `` component. The image component also requires a specified `width` and `height` in addition to the always-required `alt` property: `a cat sleeping on a bed` + +```astro title="src/pages/index.astro" +--- +import { Image } from 'astro:assets'; +import localImage1 from '~/assets/localImage.png'; +import localImage2 from '../images/subfolder/localImage2.jpg'; +--- +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. + + +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. +A bird sitting on a nest of eggs. + +``` + ## Images in Markdown @@ -29,10 +58,25 @@ The new assets experience currently features: - otherwise, use a location path relative to your `.md` file: e.g. `src/content/docs/v1/introduction.md`'s relative path to `src/images/my-image.png` is `../../../images/my-image.png` -### Images in UI framework components +## Images in MDX files + +- in `.mdx` files, you can use: + - the above methods for `.astro` files, both the HTML `` element and the `` component. Remember that the image must be imported (AFTER any YAML frontmatter), and that the import is used differently in each case (e.g. img uses `src={image.src}` and Image uses `src={image}` directly.) + - the above method for Markdown syntax. No image import is required. + +## Choosing `` vs `` -- Use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte, etc.) -- must import local images, and import still takes the shape mentioned above, so e.g. `src={myImage.src} width={myImage.width}` +- The `` component optimizes your image, infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `` element, nor does it support `srcset`. +- Use the HTML `` element when you cannot use the `` component, for example: + - for unsupported image formats, like `.svg` + - when you do not want your image optimized by Astro + - to change the `src` attribute dynamically client-side + + +## Images in UI framework components + +- Use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte, etc.) (Not ``, which as an Astro component, is unavailable in UI Frameworks) +- must import local images, and import requires specifying the value from the import, so e.g. `src={myImage.src} width={myImage.width}` ```jsx title="src/components/ReactImg.jsx" import docline from "../assets/docline.png" @@ -52,9 +96,10 @@ export default function ReactImg () { A cartoon about docs. ``` +### Passing the Image component to Framework components - can NOT use Astro's `` component because that's an ASTRO component, and you can't use Astro inside other framework components -- But, you can use the Astro slot pattern to pass static content generated by Astro components as children inside an Astro component: +- But, you can use the Astro slot pattern/children to pass static content generated by Astro components as children inside an Astro component: ```astro title="ImageSlots.astro" @@ -95,15 +140,15 @@ import Layout from '../layouts/BlogPost.astro'; ``` +## Existing stuff - -## Enabling Assets in your Project +### Enabling Assets in your Project Enabling assets may cause some breaking changes in your project. It may also require some manual changes to take advantage of new features. Please check every section below to avoid errors and to get the most out of using the experimental assets option! -### Update Config +#### Update Config To enable built-in asset support, add the following lines to your `astro.config.mjs` configuration file: @@ -124,7 +169,7 @@ When you next run Astro, it will update your `src/env.d.ts` file to configure ty /// ``` -### Move your images to `src/assets/` +#### Move your images to `src/assets/` Create `src/assets/`, which Astro will recognize as your new assets folder. @@ -132,7 +177,7 @@ We recommend storing all images to be optimized in the `src/assets/` directory t Your images can be used by components (`.astro`, `.mdx`, and other UI frameworks) and in Markdown files. -### Update existing `` tags +#### Update existing `` tags Previously, importing an image would return a simple `string` with the path of the image. With the new `image` features enabled, imported image assets now match the following signature: @@ -156,7 +201,7 @@ import rocket from '../assets/images/rocket.svg' A rocketship in space. ``` -### Update your Markdown, MDX, and Markdoc files +#### Update your Markdown, MDX, and Markdoc files Relative images can now be referenced in Markdown, MDX, and Markdoc files. These will automatically be optimized and hashed by Astro's build process. From eaea2fbf192ad98d80c8a92d75fa145533f3eb15 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 13 Jul 2023 17:07:18 +0000 Subject: [PATCH 03/58] draft - images in astro files --- src/content/docs/en/guides/assets.mdx | 242 +++++++++++++++++++++++--- 1 file changed, 218 insertions(+), 24 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 91978a812fd7d..0dd136a11f343 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -3,48 +3,242 @@ title: Assets (Experimental) description: Learn how to enable experimental asset support in Astro. i18nReady: false --- -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro' +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; -**Built-in optimized asset support** is enabled in Astro behind an experimental flag. This built-in feature will eventually replace the optional `@astrojs/image` integration. -The new assets experience currently features: +Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to remotely, or stored in a CMS or CDN! -- A new built-in `` component -- Relative images with automatic optimization in Markdown, [MDX](/en/guides/integrations-guide/mdx/), and [Markdoc](/en/guides/integrations-guide/markdoc/) -- Integration with content collections -- Improved error messages and types +## Where to store images + +### `src/` vs `public/` + +We recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. Files in the `/public` directory are always served or copied into the build folder as-is, with no processing. + +In Astro v3.0, your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Store your images in the `public/` folder only if you want to avoid any processing. + + +### `src/assets/` + +We recommend storing all local images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. + +If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), this folder ensures the greatest stability as we continue to build more asset features. But, images can be stored anywhere, including alongside your content, if you prefer. + +### Remote images + +You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. + +Astro can fetch your data remotely using APIs or display images from their full URL path. See our [CMS guides](/en/guides/cms/) for examples of integrating common services. -## New stuff - rough notes ## Images in `.astro` files -- **local images** must be imported either using the built-in alias for the `/assets/` folder: `import cat from '~/assets/funny/threads.jpg';` or the relative path from the existing astro page: `../assets/funny/threads.jpg` Required for both HTML `` and Astro ``. -- `` also requires importing the Image component from the `astro:assets` module: `import { Image } from 'astro:assets'` -- **remote images** are not imported; use their full URL as the `src` property. When using the `` component, you must specify both `width` and `height` in addition to the always-required `alt`: `a chickadee sitting on a branch with fluff in its beak` +```astro title="src/pages/blog/MyImages.astro" +--- +import { Image } from 'astro:assets'; +import localBirdImage from '~/assets/localBirdImage.png'; +import localCarImage from '../../images/subfolder/localCar.jpg'; +--- +A bird sitting on a nest of eggs. +A car driving over a bridge. +A bird. +A bird. + +A bird sitting on a nest of eggs. +A car driving over a bridge. +A bird. +A bird. +``` + +### `` (`astro:assets`) + +Use the built-in `` Astro component to display optimized versions of your images. + +```astro title="src/components/MyComponent.astro" +--- +// import the Image component and the image +import { Image } from 'astro:assets'; +import myImage from "~/assets/my_image.png"; // Image is 1600x900 +--- + + +A description of my image. +``` + +```html + + +A description of my image. +``` + +`` can transform an image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. + +:::tip[What is Cumulative Layout Shift?] +[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. +::: + +#### Properties + +##### src (required) + +The source location of your image file depends on where your image file is located: + +- **Local images in `src/`**: you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: + +```astro "myImportedImage" "{myImportedImage}" +--- +import { Image } from 'astro:assets'; +import myImportedImage from `~/assets/my-local-image.png` +--- +descriptive text +``` + +- **Images in the `public/` folder**- use the image's **file path relative to the public folder**: + +```astro '"/images/my-public-image.png"' +--- +import { Image } from 'astro:assets'; +--- +descriptive text +``` + +- **Remote images** - use the image's **full URL** as the property value: + +```astro '"https://example.com/remote-image.jpg"' +--- +import { Image } from 'astro:assets'; +--- +descriptive text +``` + +##### alt (required) + +Use the required `alt` attribute to provide a string of [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. + +If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. + +##### width and height (required for `public/` and remote images) + +These properties define the dimensions to use for the image. + +When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. + +However, both of these properties are required for remote images and images stored in your `public/` folder. + +##### format + +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used + +By default, the `` component will produce a `webp` file. -- **images in public** are not imported; use their path relative to your public folder as the `src` property, both for the HTML `` tag and for the Astro `` component. The image component also requires a specified `width` and `height` in addition to the always-required `alt` property: `a cat sleeping on a bed` +##### quality + +`quality` is an optional property that can either be: +- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. +- a number from `0` to `100` (interpreted differently between formats). + +We don't know what they mean, either. + +##### Additional properties -```astro title="src/pages/index.astro" +In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. + +For example, you can provide a `class` to the final `` element. + +```astro --- import { Image } from 'astro:assets'; -import localImage1 from '~/assets/localImage.png'; -import localImage2 from '../images/subfolder/localImage2.jpg'; +import myImage from "../assets/my_image.png"; +--- + + + +``` + +```astro + + +``` + +### `` + +The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. + +It accepts all HTML `` tag properties, and the only required property is `src`. + +#### Local images in `src/` + +Local images must be **imported from the relative path** from the existing `.astro` file, or use an [import alias](/en/guides/aliases/), such as the included `~/assets/` alias. Then, you can access the image's `src` and other properties to use in the `` tag. + +```astro ".src" "img" --- -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. +// import local images +import myCat from `~/assets/local-cat.png` +import myDog from `../../images/pets/local-dog.jpg` +--- +// access the image properties +descriptive text +descriptive text +``` +Imported image assets match the following signature: -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. -A bird sitting on a nest of eggs. +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` + +#### Images in `public/` +For images located within `public/` use the image's **file path relative to the public folder** as the `src` value: + +```astro '"/images/public-cat.jpg"' +a sleeping cat +``` + +#### Remote images +For remote images, use the image's **full URL** as the `src` value: + +```astro '"https://example.com/remote-cat.jpg"' +a sleeping cat ``` + ## Images in Markdown - in `.md` files, you must only use the `![]()` syntax to display images. @@ -61,7 +255,7 @@ import localImage2 from '../images/subfolder/localImage2.jpg'; ## Images in MDX files - in `.mdx` files, you can use: - - the above methods for `.astro` files, both the HTML `` element and the `` component. Remember that the image must be imported (AFTER any YAML frontmatter), and that the import is used differently in each case (e.g. img uses `src={image.src}` and Image uses `src={image}` directly.) + - the above methods for `.astro` files, both [the HTML `` element](#img) and [the Astro `` component](#image--astroassets). Remember that the image must be imported (AFTER any YAML frontmatter), and that the import is used differently in each case (e.g. img uses `src={image.src}` and Image uses `src={image}` directly.) - the above method for Markdown syntax. No image import is required. ## Choosing `` vs `` From 881feef0f7fd549533dec5c799e8c437b93b1601 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 13 Jul 2023 17:21:55 +0000 Subject: [PATCH 04/58] choosing image img --- src/content/docs/en/guides/assets.mdx | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 0dd136a11f343..97f20a8f96b9e 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -237,6 +237,14 @@ For remote images, use the image's **full URL** as the `src` value: /> ``` +### Choosing `` vs `` + +The `` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `` element, nor does it support `srcset`. + +Use the HTML `` element when you cannot use the `` component, for example: + - for unsupported image formats, like `.svg` + - when you do not want your image optimized by Astro + - to access and change the `src` attribute dynamically client-side ## Images in Markdown @@ -258,15 +266,6 @@ For remote images, use the image's **full URL** as the `src` value: - the above methods for `.astro` files, both [the HTML `` element](#img) and [the Astro `` component](#image--astroassets). Remember that the image must be imported (AFTER any YAML frontmatter), and that the import is used differently in each case (e.g. img uses `src={image.src}` and Image uses `src={image}` directly.) - the above method for Markdown syntax. No image import is required. -## Choosing `` vs `` - -- The `` component optimizes your image, infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `` element, nor does it support `srcset`. -- Use the HTML `` element when you cannot use the `` component, for example: - - for unsupported image formats, like `.svg` - - when you do not want your image optimized by Astro - - to change the `src` attribute dynamically client-side - - ## Images in UI framework components - Use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte, etc.) (Not ``, which as an Astro component, is unavailable in UI Frameworks) From f9a54b820475b8e2febcb7c7fbfe3962f1924fc2 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 14:17:07 +0000 Subject: [PATCH 05/58] move v3 upgrade guide stuff to bottom --- src/content/docs/en/guides/assets.mdx | 384 +++++++++++++------------- 1 file changed, 191 insertions(+), 193 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 97f20a8f96b9e..a81d0d7e79e8a 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -32,6 +32,7 @@ Astro can fetch your data remotely using APIs or display images from their full ## Images in `.astro` files +In `.astro` files, import and use the `` component for most of your images. Alternatively, Astro syntax supports writing an HTML `` tag directly. ```astro title="src/pages/blog/MyImages.astro" --- @@ -54,6 +55,12 @@ import localCarImage from '../../images/subfolder/localCar.jpg'; Use the built-in `` Astro component to display optimized versions of your images. +`` can transform an image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. + +:::tip[What is Cumulative Layout Shift?] +[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. +::: + ```astro title="src/components/MyComponent.astro" --- // import the Image component and the image @@ -78,19 +85,13 @@ import myImage from "~/assets/my_image.png"; // Image is 1600x900 /> ``` -`` can transform an image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. - -:::tip[What is Cumulative Layout Shift?] -[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. -::: - #### Properties ##### src (required) -The source location of your image file depends on where your image file is located: +The format of the `src` value of your image file depends on where your image file is located: -- **Local images in `src/`**: you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: +- **Local images in `src/`** - you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: ```astro "myImportedImage" "{myImportedImage}" --- @@ -100,7 +101,7 @@ import myImportedImage from `~/assets/my-local-image.png` descriptive text ``` -- **Images in the `public/` folder**- use the image's **file path relative to the public folder**: +- **Images in the `public/` folder** - use the image's **file path relative to the public folder**: ```astro '"/images/my-public-image.png"' --- @@ -138,11 +139,11 @@ These properties define the dimensions to use for the image. When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. -However, both of these properties are required for remote images and images stored in your `public/` folder. +However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. ##### format -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used. By default, the `` component will produce a `webp` file. @@ -247,7 +248,7 @@ Use the HTML `` element when you cannot use the `` component, for - to access and change the `src` attribute dynamically client-side -## Images in Markdown +## Images in Markdown files - in `.md` files, you must only use the `![]()` syntax to display images. - You cannot use a `` element directly, nor the Astro `` component @@ -333,19 +334,185 @@ import Layout from '../layouts/BlogPost.astro'; ``` -## Existing stuff +## `astro:assets` module - move to reference?! + +Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: + +- `` (available in `.astro` and `.mdx` files) +- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) + +:::caution +`` is an Astro component and [can't be used in framework components](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components). + +`getImage()` relies on server-only APIs and breaks the build when used on the client. +::: + +### `` (`astro:assets`) + +The `` component generates an `` tag. + +This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `` tag will include the correct `width` and `height` attributes to avoid Cumulative Layout Shift **(CLS)**. + +:::tip[What is Cumulative Layout Shift?] +CLS is a score that reflects how much content shifted on your page during loading. The ideal number for CLS is as close to zero as possible, which the `Image` component enforces by automatically selecting the correct `width` and `height` for local images. +::: + +Import images from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the `` component's `src` attribute. + +```astro +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // Image is 1600x900 +--- + + +A description of my image. +``` + +```astro + + +A description of my image. +``` + +#### Properties + +##### width and height + +These properties define the dimensions to use for the image. + +When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. However, both of these properties are required for remote images. + +##### format + +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) to be used. The default file format used is `webp`. + +##### quality + +`quality` is an optional property that can either be: +- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. +- a number from `0` to `100` (interpreted differently between formats). + +##### alt (required) + +Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. + +This attribute is required for the `` component. This 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. + +##### Additional properties + +In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. + +For example, you can provide a `class` to the final `img` element. + +```astro +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; +--- + + + +``` + +```astro + + +``` + +### `getImage()` (`astro:assets`) + +This 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. + +`getImage()` takes an options object with the same properties as the Image component (except `alt`). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +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..) +} +``` + +## Using sharp - update how this works! + +By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. This supports all JavaScript environments. + +If you're deploying to a Node environment, you may want to use [sharp](https://github.com/lovell/sharp), which offers faster performance but requires Node. To use sharp, first install it: + + + + ```shell + npm install sharp + ``` + + + ```shell + pnpm install sharp + ``` + + + ```shell + yarn add sharp + ``` + + + +Then, enable Astro's sharp image service in your config: + +```js title="astro.config.mjs" +import { defineConfig, sharpImageService } from "astro/config"; + +export default defineConfig({ + experimental: { + assets: true, + }, + image: { + service: sharpImageService(), + }, +}); +``` -### Enabling Assets in your Project +## v3 update guide stuff -Enabling assets may cause some breaking changes in your project. It may also require some manual changes to take advantage of new features. +Assets may cause some breaking changes when you upgrade your Astro project to v3. -Please check every section below to avoid errors and to get the most out of using the experimental assets option! -#### Update Config +### Update Config -To enable built-in asset support, add the following lines to your `astro.config.mjs` configuration file: +Remove the experimental flag if you previously had it -```js title="astro.config.mjs" ins={4-6} +```js title="astro.config.mjs" del={4-6} import { defineConfig } from 'astro/config'; export default defineConfig({ @@ -362,7 +529,7 @@ When you next run Astro, it will update your `src/env.d.ts` file to configure ty /// ``` -#### Move your images to `src/assets/` +### Move your images to `src/assets/` Create `src/assets/`, which Astro will recognize as your new assets folder. @@ -370,7 +537,7 @@ We recommend storing all images to be optimized in the `src/assets/` directory t Your images can be used by components (`.astro`, `.mdx`, and other UI frameworks) and in Markdown files. -#### Update existing `` tags +### Update existing `` tags Previously, importing an image would return a simple `string` with the path of the image. With the new `image` features enabled, imported image assets now match the following signature: @@ -394,7 +561,7 @@ import rocket from '../assets/images/rocket.svg' A rocketship in space. ``` -#### Update your Markdown, MDX, and Markdoc files +### Update your Markdown, MDX, and Markdoc files Relative images can now be referenced in Markdown, MDX, and Markdoc files. These will automatically be optimized and hashed by Astro's build process. @@ -418,7 +585,7 @@ Your existing images in `public/` and remote images are still valid but are not Astro logo ``` -### Convert from `@astrojs/image` +### Remove `@astrojs/image` **Built-in asset support is incompatible with the `@astrojs/image` integration.** @@ -519,173 +686,4 @@ const allBlogPosts = await getCollection("blog"); )) } -``` - -## `astro:assets` module - -Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: - -- `` (available in `.astro` and `.mdx` files) -- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) - -:::caution -`` is an Astro component and [can't be used in framework components](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components). - -`getImage()` relies on server-only APIs and breaks the build when used on the client. -::: - -### `` (`astro:assets`) - -The `` component generates an `` tag. - -This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `` tag will include the correct `width` and `height` attributes to avoid Cumulative Layout Shift **(CLS)**. - -:::tip[What is Cumulative Layout Shift?] -CLS is a score that reflects how much content shifted on your page during loading. The ideal number for CLS is as close to zero as possible, which the `Image` component enforces by automatically selecting the correct `width` and `height` for local images. -::: - -Import images from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the `` component's `src` attribute. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - - -A description of my image. -``` - -```astro - - -A description of my image. -``` - -#### Properties - -##### width and height - -These properties define the dimensions to use for the image. - -When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. However, both of these properties are required for remote images. - -##### format - -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) to be used. The default file format used is `webp`. - -##### quality - -`quality` is an optional property that can either be: -- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. -- a number from `0` to `100` (interpreted differently between formats). - -##### alt (required) - -Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. - -This attribute is required for the `` component. This 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. - -##### Additional properties - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -For example, you can provide a `class` to the final `img` element. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; ---- - - - -``` - -```astro - - -``` - -### `getImage()` (`astro:assets`) - -This 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. - -`getImage()` takes an options object with the same properties as the Image component (except `alt`). - -```astro ---- -import { getImage } from "astro:assets"; -import myBackground from "../background.png" - -const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) ---- - -
-``` - -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..) -} -``` - -## Using sharp - -By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. This supports all JavaScript environments. - -If you're deploying to a Node environment, you may want to use [sharp](https://github.com/lovell/sharp), which offers faster performance but requires Node. To use sharp, first install it: - - - - ```shell - npm install sharp - ``` - - - ```shell - pnpm install sharp - ``` - - - ```shell - yarn add sharp - ``` - - - -Then, enable Astro's sharp image service in your config: - -```js title="astro.config.mjs" -import { defineConfig, sharpImageService } from "astro/config"; - -export default defineConfig({ - experimental: { - assets: true, - }, - image: { - service: sharpImageService(), - }, -}); -``` +``` \ No newline at end of file From 8ea2125e62113e7b586b7021db7a59881bdd1831 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 14:48:04 +0000 Subject: [PATCH 06/58] draft - images in markdown files --- src/content/docs/en/guides/assets.mdx | 33 +++++++++++++++++++-------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index a81d0d7e79e8a..d79ecd41829ed 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -250,16 +250,29 @@ Use the HTML `` element when you cannot use the `` component, for ## Images in Markdown files -- in `.md` files, you must only use the `![]()` syntax to display images. -- You cannot use a `` element directly, nor the Astro `` component -- the images can be: - - remote images, using a full URL e.g. `![](https://example.com/images/remote-image.png)` - - images stored in `public/`, using the URL path relative to the public directory e.g. `![](/assets/images/my-public-image.jpg)` for `public/assets/images/my-public-image.jpg` - - local images in `src/`, using a relative path to the image from the file you're currently in - - if located in `src/assets/` you can use the `~/assets/my-image.png` alias - - if co-located in the same folder as your `.md` file, use `./my-image.png` - - otherwise, use a location path relative to your `.md` file: - e.g. `src/content/docs/v1/introduction.md`'s relative path to `src/images/my-image.png` is `../../../images/my-image.png` +Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's Image Services API to optimize your local images. + +```md + + +# My Markdown Page + + + +![A starry night sky.](~/assets/stars.png) + + + +![A starry night sky.](/images/stars.png) + + + +![Astro](https://example.com/images/remote-image.png) +``` + +The `` tag is not supported, nor is the `` component. + +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. ## Images in MDX files From 405af56d5ef8cc709cb31290853432b202ffd42c Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 15:11:16 +0000 Subject: [PATCH 07/58] draft - images in mdx --- src/content/docs/en/guides/assets.mdx | 33 ++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index d79ecd41829ed..3874cd898764c 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -276,9 +276,36 @@ If you require more control over your image attributes, we recommend using the ` ## Images in MDX files -- in `.mdx` files, you can use: - - the above methods for `.astro` files, both [the HTML `` element](#img) and [the Astro `` component](#image--astroassets). Remember that the image must be imported (AFTER any YAML frontmatter), and that the import is used differently in each case (e.g. img uses `src={image.src}` and Image uses `src={image}` directly.) - - the above method for Markdown syntax. No image import is required. +You can use Astro's `` component and JSX `` tags in your `.mdx` files by importing both the component and your image. Use them just as they are [used in `.astro` files](#images-in-astro-files). + +Additionally, there is support for [standard Markdown `![alt](src)` syntax](#images-in-markdown-files) with no import required. + +```mdx title="src/pages/post-1.mdx" +--- +title: My Page title +--- +import { Image } from 'astro:assets'; +import rocket from '~/assets/rocket.png'; + +# My MDX Page + +// Local image stored in src/assets/ +A rocketship in space. +A rocketship in space. +![A rocketship in space](~/assets/rocket.png) + +// Image stored in public/images/ +A starry night sky. +A starry night sky. +![A starry night sky.](/images/stars.png) + + +// Remote image on another server + + +![Astro](https://example.com/images/remote-image.png) + +``` ## Images in UI framework components From 95f35b5737353cb2feca1e7972e2d8f79e7c859f Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 15:52:11 +0000 Subject: [PATCH 08/58] draft - images in framework components --- src/content/docs/en/guides/assets.mdx | 60 +++++++++------------------ 1 file changed, 19 insertions(+), 41 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 3874cd898764c..a74e4e5d3c8d3 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -309,71 +309,49 @@ import rocket from '~/assets/rocket.png'; ## Images in UI framework components -- Use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte, etc.) (Not ``, which as an Astro component, is unavailable in UI Frameworks) -- must import local images, and import requires specifying the value from the import, so e.g. `src={myImage.src} width={myImage.width}` +When adding images in a UI framework component, use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte). -```jsx title="src/components/ReactImg.jsx" -import docline from "../assets/docline.png" +Local images must **first be imported** to access their properties, just as when [using the `` tag in `.astro` files](#img). -export default function ReactImg () { +```jsx title="src/components/ReactImage.jsx" +import stars from "~/assets/stars.png" + +export default function ReactImgage () { return ( - A cartoon about docs. + A starry night sky. ) } ``` -```svelte title="src/components/SvelteImg.svelte" +```svelte title="src/components/SvelteImage.svelte" -A cartoon about docs. +A starry night sky. + ``` -### Passing the Image component to Framework components -- can NOT use Astro's `` component because that's an ASTRO component, and you can't use Astro inside other framework components -- But, you can use the Astro slot pattern/children to pass static content generated by Astro components as children inside an Astro component: +### Passing the Image component + +The `` component, like any other Astro component, is unavailable to UI framework components. + +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 title="ImageSlots.astro" +```astro title="ImageWrapper.astro" --- import ReactComponent from './ReactComponent.jsx'; import { Image } from "astro:assets" -import docline from "~/assets/docline.png"; -import SvelteImg from './SvelteImg.svelte'; +import stars from "~/stars/docline.png"; --- -

Using Astro's Image component

- text -

Using a Svelte Image component

- + A starry night sky.
``` -```jsx title="ReactComponent.jsx" -export default function ReactComponent ({children}) { - return ( - <> -

Some image tests

-
{children}
- - ) -} -``` - -```astro title="MyAstroPage.astro" ---- -import ImageSlots from '../components/ImageSlots.astro'; -import Layout from '../layouts/BlogPost.astro'; ---- - - - - -``` - ## `astro:assets` module - move to reference?! Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: From d1f9ef1dea7191bc33c83c9c1c6b261792769e07 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 16:10:59 +0000 Subject: [PATCH 09/58] sprinkled a few more only local images optimized --- src/content/docs/en/guides/assets.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index a74e4e5d3c8d3..523dbcd26004b 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -32,7 +32,7 @@ Astro can fetch your data remotely using APIs or display images from their full ## Images in `.astro` files -In `.astro` files, import and use the `` component for most of your images. Alternatively, Astro syntax supports writing an HTML `` tag directly. +In `.astro` files, import and use the `` component for your images. Alternatively, Astro syntax supports writing an HTML `` tag directly. ```astro title="src/pages/blog/MyImages.astro" --- @@ -53,9 +53,9 @@ import localCarImage from '../../images/subfolder/localCar.jpg'; ### `` (`astro:assets`) -Use the built-in `` Astro component to display optimized versions of your images. +Use the built-in `` Astro component to display optimized versions of your local images. Remote images and images in the `public/` folder can also be used, but will not be processed. -`` can transform an image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. +`` can transform a local image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. :::tip[What is Cumulative Layout Shift?] [Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. @@ -139,7 +139,7 @@ These properties define the dimensions to use for the image. When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. -However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. +However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. These images will not be optimized. ##### format @@ -186,7 +186,7 @@ import myImage from "../assets/my_image.png"; ### `` -The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. +The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. Local images will be optimized. It accepts all HTML `` tag properties, and the only required property is `src`. From 8b66fc7e8882cc4668d5eafa231f9df84a9f57e1 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 16:31:58 +0000 Subject: [PATCH 10/58] added and updates setting defaults on image component --- src/content/docs/en/guides/assets.mdx | 261 ++++++++++++++++---------- 1 file changed, 158 insertions(+), 103 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 523dbcd26004b..c4419878c4f15 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -184,6 +184,28 @@ import myImage from "../assets/my_image.png"; /> ``` +#### Setting Default Values + +Currently, there is no way to specify default values for all `` 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 { Image } from 'astro:assets'; + +const {src, ...attrs} = Astro.props; +--- + + + +``` + ### `` The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. Local images will be optimized. @@ -352,112 +374,13 @@ import stars from "~/stars/docline.png"; ``` -## `astro:assets` module - move to reference?! - -Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: - -- `` (available in `.astro` and `.mdx` files) -- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) +## Generating images with `getImage()` :::caution -`` is an Astro component and [can't be used in framework components](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components). - `getImage()` relies on server-only APIs and breaks the build when used on the client. ::: -### `` (`astro:assets`) - -The `` component generates an `` tag. - -This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `` tag will include the correct `width` and `height` attributes to avoid Cumulative Layout Shift **(CLS)**. - -:::tip[What is Cumulative Layout Shift?] -CLS is a score that reflects how much content shifted on your page during loading. The ideal number for CLS is as close to zero as possible, which the `Image` component enforces by automatically selecting the correct `width` and `height` for local images. -::: - -Import images from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the `` component's `src` attribute. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; // Image is 1600x900 ---- - - -A description of my image. -``` - -```astro - - -A description of my image. -``` - -#### Properties - -##### width and height - -These properties define the dimensions to use for the image. - -When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. However, both of these properties are required for remote images. - -##### format - -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) to be used. The default file format used is `webp`. - -##### quality - -`quality` is an optional property that can either be: -- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. -- a number from `0` to `100` (interpreted differently between formats). - -##### alt (required) - -Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. - -This attribute is required for the `` component. This 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. - -##### Additional properties - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -For example, you can provide a `class` to the final `img` element. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; ---- - - - -``` - -```astro - - -``` - -### `getImage()` (`astro:assets`) - -This 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. +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. `getImage()` takes an options object with the same properties as the Image component (except `alt`). @@ -482,7 +405,7 @@ It returns an object with the following properties: } ``` -## Using sharp - update how this works! +## Using sharp - STILL WORKS LIKE THIS?? By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. This supports all JavaScript environments. @@ -704,4 +627,136 @@ const allBlogPosts = await getCollection("blog"); )) } -``` \ No newline at end of file +``` + +## Add reference content somewhere?? + +### `astro:assets` module + +Enabling asset support allows you to access the `astro:assets` module. This module exposes the following features: + +- `` (available in `.astro` and `.mdx` files) +- `getImage()` (available in `.astro`, `.mdx`, `.ts`, `.js` on the server) + +:::caution +`` is an Astro component and [can't be used in framework components](/en/core-concepts/framework-components/#can-i-use-astro-components-inside-my-framework-components). + +`getImage()` relies on server-only APIs and breaks the build when used on the client. +::: + +### `` (`astro:assets`) + +The `` component generates an `` tag. + +This component can transform an image's dimensions, file type, and quality to produce an optimized image. The resulting `` tag will include the correct `width` and `height` attributes to avoid Cumulative Layout Shift **(CLS)**. + +:::tip[What is Cumulative Layout Shift?] +CLS is a score that reflects how much content shifted on your page during loading. The ideal number for CLS is as close to zero as possible, which the `Image` component enforces by automatically selecting the correct `width` and `height` for local images. +::: + +Import images from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the `` component's `src` attribute. + +```astro +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // Image is 1600x900 +--- + + +A description of my image. +``` + +```astro + + +A description of my image. +``` + +#### Properties + +##### width and height + +These properties define the dimensions to use for the image. + +When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. However, both of these properties are required for remote images. + +##### format + +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) to be used. The default file format used is `webp`. + +##### quality + +`quality` is an optional property that can either be: +- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. +- a number from `0` to `100` (interpreted differently between formats). + +##### alt (required) + +Use the `alt` attribute to provide [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. + +This attribute is required for the `` component. This 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. + +##### Additional properties + +In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. + +For example, you can provide a `class` to the final `img` element. + +```astro +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; +--- + + + +``` + +```astro + + +``` + +### `getImage()` (`astro:assets`) + +This 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. + +`getImage()` takes an options object with the same properties as the Image component (except `alt`). + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +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..) +} +``` From 904b1d6702f88227363eac555f554e44b7bc8ece Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 16:36:27 +0000 Subject: [PATCH 11/58] carried over other Images page sections --- src/content/docs/en/guides/assets.mdx | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index c4419878c4f15..399573001f4ed 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -444,6 +444,26 @@ export default defineConfig({ }); ``` +## Using Images from a CMS or CDN + +Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. + +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 an `` tag with the appropriate `src` for you. + +## 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 `` 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. + + +## Community Integrations + +There are several third-party [community image integrations](https://astro.build/integrations?search=images) for optimizing and working with images in your Astro project. + + ## v3 update guide stuff Assets may cause some breaking changes when you upgrade your Astro project to v3. From 21b4f99c33e4a900d1f8925f9b4817a633e0b8da Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Fri, 14 Jul 2023 16:48:56 +0000 Subject: [PATCH 12/58] split pages: images guide and other to be used elsewhere --- src/content/docs/en/guides/assets.mdx | 460 ---------------------- src/content/docs/en/guides/images.mdx | 530 +++++++++++++++----------- src/i18n/en/nav.ts | 2 +- 3 files changed, 310 insertions(+), 682 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index 399573001f4ed..f35393c34948e 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -3,466 +3,6 @@ title: Assets (Experimental) description: Learn how to enable experimental asset support in Astro. i18nReady: false --- -import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; - - -Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to remotely, or stored in a CMS or CDN! - -## Where to store images - -### `src/` vs `public/` - -We recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. Files in the `/public` directory are always served or copied into the build folder as-is, with no processing. - -In Astro v3.0, your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Store your images in the `public/` folder only if you want to avoid any processing. - - -### `src/assets/` - -We recommend storing all local images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. - -If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), this folder ensures the greatest stability as we continue to build more asset features. But, images can be stored anywhere, including alongside your content, if you prefer. - -### Remote images - -You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. - -Astro can fetch your data remotely using APIs or display images from their full URL path. See our [CMS guides](/en/guides/cms/) for examples of integrating common services. - - -## Images in `.astro` files - -In `.astro` files, import and use the `` component for your images. Alternatively, Astro syntax supports writing an HTML `` tag directly. - -```astro title="src/pages/blog/MyImages.astro" ---- -import { Image } from 'astro:assets'; -import localBirdImage from '~/assets/localBirdImage.png'; -import localCarImage from '../../images/subfolder/localCar.jpg'; ---- -A bird sitting on a nest of eggs. -A car driving over a bridge. -A bird. -A bird. - -A bird sitting on a nest of eggs. -A car driving over a bridge. -A bird. -A bird. -``` - -### `` (`astro:assets`) - -Use the built-in `` Astro component to display optimized versions of your local images. Remote images and images in the `public/` folder can also be used, but will not be processed. - -`` can transform a local image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. - -:::tip[What is Cumulative Layout Shift?] -[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. -::: - -```astro title="src/components/MyComponent.astro" ---- -// import the Image component and the image -import { Image } from 'astro:assets'; -import myImage from "~/assets/my_image.png"; // Image is 1600x900 ---- - - -A description of my image. -``` - -```html - - -A description of my image. -``` - -#### Properties - -##### src (required) - -The format of the `src` value of your image file depends on where your image file is located: - -- **Local images in `src/`** - you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: - -```astro "myImportedImage" "{myImportedImage}" ---- -import { Image } from 'astro:assets'; -import myImportedImage from `~/assets/my-local-image.png` ---- -descriptive text -``` - -- **Images in the `public/` folder** - use the image's **file path relative to the public folder**: - -```astro '"/images/my-public-image.png"' ---- -import { Image } from 'astro:assets'; ---- -descriptive text -``` - -- **Remote images** - use the image's **full URL** as the property value: - -```astro '"https://example.com/remote-image.jpg"' ---- -import { Image } from 'astro:assets'; ---- -descriptive text -``` - -##### alt (required) - -Use the required `alt` attribute to provide a string of [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. - -If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. - -##### width and height (required for `public/` and remote images) - -These properties define the dimensions to use for the image. - -When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. - -However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. These images will not be optimized. - -##### format - -You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used. - -By default, the `` component will produce a `webp` file. - -##### quality - -`quality` is an optional property that can either be: -- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. -- a number from `0` to `100` (interpreted differently between formats). - -We don't know what they mean, either. - -##### Additional properties - -In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. - -For example, you can provide a `class` to the final `` element. - -```astro ---- -import { Image } from 'astro:assets'; -import myImage from "../assets/my_image.png"; ---- - - - -``` - -```astro - - -``` - -#### Setting Default Values - -Currently, there is no way to specify default values for all `` 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 { Image } from 'astro:assets'; - -const {src, ...attrs} = Astro.props; ---- - - - -``` - -### `` - -The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. Local images will be optimized. - -It accepts all HTML `` tag properties, and the only required property is `src`. - -#### Local images in `src/` - -Local images must be **imported from the relative path** from the existing `.astro` file, or use an [import alias](/en/guides/aliases/), such as the included `~/assets/` alias. Then, you can access the image's `src` and other properties to use in the `` tag. - -```astro ".src" "img" ---- -// import local images -import myCat from `~/assets/local-cat.png` -import myDog from `../../images/pets/local-dog.jpg` ---- -// access the image properties -descriptive text -descriptive text -``` - -Imported image assets match the following signature: - -```ts -interface ImageMetadata { - src: string; - width: number; - height: number; - format: string; -} -``` - -#### Images in `public/` -For images located within `public/` use the image's **file path relative to the public folder** as the `src` value: - -```astro '"/images/public-cat.jpg"' -a sleeping cat -``` - -#### Remote images - -For remote images, use the image's **full URL** as the `src` value: - -```astro '"https://example.com/remote-cat.jpg"' -a sleeping cat -``` - -### Choosing `` vs `` - -The `` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `` element, nor does it support `srcset`. - -Use the HTML `` element when you cannot use the `` component, for example: - - for unsupported image formats, like `.svg` - - when you do not want your image optimized by Astro - - to access and change the `src` attribute dynamically client-side - - -## Images in Markdown files - -Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's Image Services API to optimize your local images. - -```md - - -# My Markdown Page - - - -![A starry night sky.](~/assets/stars.png) - - - -![A starry night sky.](/images/stars.png) - - - -![Astro](https://example.com/images/remote-image.png) -``` - -The `` tag is not supported, nor is the `` component. - -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. - -## Images in MDX files - -You can use Astro's `` component and JSX `` tags in your `.mdx` files by importing both the component and your image. Use them just as they are [used in `.astro` files](#images-in-astro-files). - -Additionally, there is support for [standard Markdown `![alt](src)` syntax](#images-in-markdown-files) with no import required. - -```mdx title="src/pages/post-1.mdx" ---- -title: My Page title ---- -import { Image } from 'astro:assets'; -import rocket from '~/assets/rocket.png'; - -# My MDX Page - -// Local image stored in src/assets/ -A rocketship in space. -A rocketship in space. -![A rocketship in space](~/assets/rocket.png) - -// Image stored in public/images/ -A starry night sky. -A starry night sky. -![A starry night sky.](/images/stars.png) - - -// Remote image on another server - - -![Astro](https://example.com/images/remote-image.png) - -``` - -## Images in UI framework components - -When adding images in a UI framework component, use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte). - -Local images must **first be imported** to access their properties, just as when [using the `` tag in `.astro` files](#img). - -```jsx title="src/components/ReactImage.jsx" -import stars from "~/assets/stars.png" - -export default function ReactImgage () { - - return ( - A starry night sky. - ) -} -``` - -```svelte title="src/components/SvelteImage.svelte" - - -A starry night sky. - -``` - -### Passing the Image component - -The `` component, like any other Astro component, is unavailable to UI framework components. - -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 title="ImageWrapper.astro" ---- -import ReactComponent from './ReactComponent.jsx'; -import { Image } from "astro:assets" -import stars from "~/stars/docline.png"; ---- - - - A starry night sky. - -``` - -## Generating images with `getImage()` - -:::caution -`getImage()` relies on server-only APIs and breaks the build when used on the client. -::: - -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. - -`getImage()` takes an options object with the same properties as the Image component (except `alt`). - -```astro ---- -import { getImage } from "astro:assets"; -import myBackground from "../background.png" - -const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) ---- - -
-``` - -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..) -} -``` - -## Using sharp - STILL WORKS LIKE THIS?? - -By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. This supports all JavaScript environments. - -If you're deploying to a Node environment, you may want to use [sharp](https://github.com/lovell/sharp), which offers faster performance but requires Node. To use sharp, first install it: - - - - ```shell - npm install sharp - ``` - - - ```shell - pnpm install sharp - ``` - - - ```shell - yarn add sharp - ``` - - - -Then, enable Astro's sharp image service in your config: - -```js title="astro.config.mjs" -import { defineConfig, sharpImageService } from "astro/config"; - -export default defineConfig({ - experimental: { - assets: true, - }, - image: { - service: sharpImageService(), - }, -}); -``` - -## Using Images from a CMS or CDN - -Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. - -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 an `` tag with the appropriate `src` for you. - -## 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 `` 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. - - -## Community Integrations - -There are several third-party [community image integrations](https://astro.build/integrations?search=images) for optimizing and working with images in your Astro project. - ## v3 update guide stuff diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index d3700943dbcfc..a5232b79ebf24 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -4,375 +4,463 @@ description: Learn how to use images in Astro. i18nReady: true --- import Since from '~/components/Since.astro'; +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; Astro provides several ways for you to use images on your site, whether they are stored locally inside your project, linked to remotely, or stored in a CMS or CDN! -:::note[using Assets (Experimental)] -Experimental asset support was added in `astro@2.1.0`. If you have enabled assets support, see the [Assets (Experimental) Guide](/en/guides/assets/) for extra information. +## Where to store images -**Some of the advice below is incompatible with the experimental flag.** -::: +### `src/` vs `public/` -### In `.astro` files +We recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. Files in the `/public` directory are always served or copied into the build folder as-is, with no processing. -Astro uses HTML `` elements to display images, and all HTML image attributes are supported. +In Astro v3.0, your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Store your images in the `public/` folder only if you want to avoid any processing. -The `src` attribute is required, and its format will depend on where your images are stored, and whether you have enabled experimental support for assets: -```astro title="src/pages/index.astro" ---- -import rocket from '../images/rocket.svg'; ---- - -Astro +### `src/assets/` - -A starry night sky. +We recommend storing all local images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. - -A rocketship in space. -``` +If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), this folder ensures the greatest stability as we continue to build more asset features. But, images can be stored anywhere, including alongside your content, if you prefer. -### In Markdown files +### Remote images -You can use standard Markdown `![]()` syntax or standard HTML `` tags in your `.md` files for images located in your `public/` folder, or remote images on another server. +You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. -If you cannot keep your images in `public/`, we recommend enabling [experimental support for assets](/en/guides/assets/), or using the `.mdx` file format, which allows you to combine imported components with Markdown-like syntax. Use the [MDX integration](/en/guides/integrations-guide/mdx/) to add support for MDX to Astro. +Astro can fetch your data remotely using APIs or display images from their full URL path. See our [CMS guides](/en/guides/cms/) for examples of integrating common services. -```md - -# My Markdown Page +## Images in `.astro` files - -![A starry night sky.](/assets/stars.png) -A starry night sky. +In `.astro` files, import and use the `` component for your images. Alternatively, Astro syntax supports writing an HTML `` tag directly. - -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro +```astro title="src/pages/blog/MyImages.astro" +--- +import { Image } from 'astro:assets'; +import localBirdImage from '~/assets/localBirdImage.png'; +import localCarImage from '../../images/subfolder/localCar.jpg'; +--- +A bird sitting on a nest of eggs. +A car driving over a bridge. +A bird. +A bird. + +A bird sitting on a nest of eggs. +A car driving over a bridge. +A bird. +A bird. ``` -### In MDX files - -You can use standard Markdown `![]()` syntax or JSX `` tags in your `.mdx` files to display images from your `public/` folder or remote servers. - -Additionally, you can import and use images located in your project's `src/` directory, as you would in Astro components. +### `` (`astro:assets`) -```mdx title="src/pages/post-1.mdx" - -import rocket from '../images/rocket.svg'; +Use the built-in `` Astro component to display optimized versions of your local images. Remote images and images in the `public/` folder can also be used, but will not be processed. -# My MDX Page +`` can transform a local image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. -// Local image stored at src/images/rocket.svg -A rocketship in space. +:::tip[What is Cumulative Layout Shift?] +[Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. +::: -// Local image stored at public/assets/stars.png -![A starry night sky.](/assets/stars.png) -A starry night sky. +```astro title="src/components/MyComponent.astro" +--- +// import the Image component and the image +import { Image } from 'astro:assets'; +import myImage from "~/assets/my_image.png"; // Image is 1600x900 +--- -// Remote image on another server -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro + +A description of my image. ``` -### In UI Framework Components - -When adding images in a [UI framework component](/en/core-concepts/framework-components/) (e.g React, Svelte), use the image syntax appropriate for that particular component's framework. - -## Where to store images - -### `src/` +```html + + +A description of my image. +``` -Your images stored in `src/` can be used by components (`.astro`, `.mdx` and other UI frameworks) but not in Markdown files. +#### Properties -We recommend that you keep your images in [`public/`](#public) or store them [remotely](#using-images-from-a-cms-or-cdn) if you must use Markdown files. +##### src (required) -Import them from a **relative file path** or [import alias](/en/guides/aliases/) in any component file and then use the import as the image's `src` attribute. +The format of the `src` value of your image file depends on where your image file is located: +- **Local images in `src/`** - you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: -```astro +```astro "myImportedImage" "{myImportedImage}" --- -// src/pages/index.astro - -// Access images in `src/images/` -import logo from '../images/logo.png'; +import { Image } from 'astro:assets'; +import myImportedImage from `~/assets/my-local-image.png` --- -Astro +descriptive text ``` -### `public/` +- **Images in the `public/` folder** - use the image's **file path relative to the public folder**: -Your images stored in `public/` can be used by components (`.astro`, `.mdx` and other UI frameworks) and also Markdown files. - - -However, files in the `/public` directory are always served or copied as-is, with no processing. If you are using images outside of Markdown files, we recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. +```astro '"/images/my-public-image.png"' +--- +import { Image } from 'astro:assets'; +--- +descriptive text +``` -The `src` attribute is **relative to the public folder**. In Markdown, you can also use the `![]()` notation. +- **Remote images** - use the image's **full URL** as the property value: -```astro title="src/pages/index.astro" +```astro '"https://example.com/remote-image.jpg"' --- -// Access images in `public/images/` +import { Image } from 'astro:assets'; --- - +descriptive text ``` -### `src/assets/` (experimental) +##### alt (required) -See the [Assets (Experimental)](/en/guides/assets/) guide for enabling experimental use of the `/assets/` folder. +Use the required `alt` attribute to provide a string of [descriptive alt text](https://www.w3.org/WAI/tutorials/images/) for images. -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. +If an image is merely decorative (i.e. doesn't contribute to the understanding of the page), set `alt=""` so that screen readers and other assistive technologies know to ignore the image. -## Astro's Image Integration +##### width and height (required for `public/` and remote images) -Astro's official image integration provides two different Astro components for rendering optimized images, `` and ``. It is supported for all static sites and for [some server-side rendering deploy hosts](/en/guides/integrations-guide/image/#installation). +These properties define the dimensions to use for the image. -After [installing `@astrojs/image`](/en/guides/integrations-guide/image/#installation), you can use these two components wherever you can use Astro components: in `.astro` and `.mdx` files. +When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. -:::note[incompatible with assets] -If you have enabled experimental asset support, then you must uninstall the official integration. See the [Assets (Experimental) Guide](/en/guides/assets/) for more information. -::: +However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. These images will not be optimized. -### `` +##### format -Astro's [`` component](/en/guides/integrations-guide/image/#image-) allows you to optimize a single image and specify width, height, and/or aspect ratio. You can even transform your image to a particular output format. +You can optionally state the [image file type](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) output to be used. -This component is useful for images where you want to keep a consistent size across displays, or closely control the quality of an image (e.g. logos). +By default, the `` component will produce a `webp` file. -For responsive images, or art direction, use the `` component instead. +##### quality -#### Remote Images +`quality` is an optional property that can either be: +- a preset (`low`, `mid`, `high`, `max`) that is automatically normalized between formats. +- a number from `0` to `100` (interpreted differently between formats). -(required attributes: [`src`](/en/guides/integrations-guide/image/#src), [`alt`](/en/guides/integrations-guide/image/#alt), [`format`](/en/guides/integrations-guide/image/#format), and dimensions) +We don't know what they mean, either. -Pass a full URL to the `` component's `src` attribute and include a value for `alt`. +##### Additional properties -The `` component cannot determine the original file format of a remote image, so you must provide an output `format` (e.g. png, avif) to transform your remote image. +In addition to the properties above, the `` component accepts all properties accepted by the HTML `` tag. -You must also either provide [`width`](/en/guides/integrations-guide/image/#width) and [`height`](/en/guides/integrations-guide/image/#height), or one of the dimensions plus an [`aspectRatio`](/en/guides/integrations-guide/image/#aspectratio) to avoid content layout shifts because the `` component does not know the dimensions of a remote image. +For example, you can provide a `class` to the final `` element. -[All other properties](/en/guides/integrations-guide/image/#image-) are optional. +```astro +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; +--- -#### Local Images in `src/` + + +``` -(required attributes: [`src`](/en/guides/integrations-guide/image/#src), and [`alt`](/en/guides/integrations-guide/image/#alt)) +```astro + + +``` -Import your image in frontmatter and pass it directly to the `` component's `src` attribute. +#### Setting Default Values -`alt` is required, but [all other properties](/en/guides/integrations-guide/image/#image-) are optional and will default to the image file's original properties if not provided. +Currently, there is no way to specify default values for all `` components. Required attributes should be set on each individual component. -#### Images in `public/` +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: -(required attributes: [`src`](/en/guides/integrations-guide/image/#src), [`alt`](/en/guides/integrations-guide/image/#alt), [`format`](/en/guides/integrations-guide/image/#format), and dimensions) +```astro title="src/components/BlogPostImage.astro" +--- +import { Image } from 'astro:assets'; -Pass the component's `src` attribute a path relative to the public folder and include a value for `alt`. +const {src, ...attrs} = Astro.props; +--- + + + +``` -It will be treated as a remote image, which requires either both [`width`](/en/guides/integrations-guide/image/#width) and [`height`](/en/guides/integrations-guide/image/#height), or one dimension and an [`aspectRatio`](/en/guides/integrations-guide/image/#aspectratio) attribute. +### `` -A value for the `format` attribute (e.g. png, avif) to transform your image is required. +The [Astro template syntax](/en/core-concepts/astro-syntax/) also supports writing an `` tag directly, with full control over its final output. Local images will be optimized. -[All other properties](/en/guides/integrations-guide/image/#image-) are optional. +It accepts all HTML `` tag properties, and the only required property is `src`. -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. +#### Local images in `src/` -#### Examples +Local images must be **imported from the relative path** from the existing `.astro` file, or use an [import alias](/en/guides/aliases/), such as the included `~/assets/` alias. Then, you can access the image's `src` and other properties to use in the `` tag. -```astro +```astro ".src" "img" --- -// 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"; +// import local images +import myCat from `~/assets/local-cat.png` +import myDog from `../../images/pets/local-dog.jpg` --- +// access the image properties +descriptive text +descriptive text +``` - -{localAlt} +Imported image assets match the following signature: - -{localAlt} +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` - -{remoteAlt} +#### Images in `public/` +For images located within `public/` use the image's **file path relative to the public folder** as the `src` value: - -{localAlt}/ -{remoteAlt}/ +```astro '"/images/public-cat.jpg"' +a sleeping cat +``` - -{localAlt}/ -{remoteAlt}/ +#### Remote images - -{localAlt}/ +For remote images, use the image's **full URL** as the `src` value: - -A happy penguin +```astro '"https://example.com/remote-cat.jpg"' +a sleeping cat ``` -### ` ` +### Choosing `` vs `` -Astro's [`` component](/en/guides/integrations-guide/image/#picture-) can be used to provide responsive images on your site, including multiple image sizes, formats, and layouts. +The `` component optimizes your image and infers width and height (of local images) based on the original aspect ratio to avoid CLS. But, it only works with certain formats and does not provide a `` element, nor does it support `srcset`. -You can let the user's browser choose appropriate image sizes, resolutions, and file types based on factors like screen size and bandwidth. Or, you can specify rules that the browser must follow based on media queries. +Use the HTML `` element when you cannot use the `` component, for example: + - for unsupported image formats, like `.svg` + - when you do not want your image optimized by Astro + - to access and change the `src` attribute dynamically client-side -This component is useful to optimize what your user sees at various screen sizes, or for art direction. -:::tip -Check out MDN's guide for more information about [responsive images and art direction](https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction). -::: +## Images in Markdown files -#### Remote Images +Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's Image Services API to optimize your local images. -(required attributes: [`src`](/en/guides/integrations-guide/image/#src-1), [`widths`](/en/guides/integrations-guide/image/#widths), [`sizes`](/en/guides/integrations-guide/image/#sizes), [`alt`](/en/guides/integrations-guide/image/#alt-1), and [`aspectRatio`](/en/guides/integrations-guide/image/#aspectratio-1)) +```md + -Pass a full URL to the `` component's `src` attribute. +# My Markdown Page -A value for `aspectRatio` is also required to ensure the correct height can be calculated at build time for remote images. + + +![A starry night sky.](~/assets/stars.png) -You must provide the component with guidance for image widths and screen sizes, but [all other properties](/en/guides/integrations-guide/image/#picture-) are optional. + + +![A starry night sky.](/images/stars.png) -Although [`formats`](/en/guides/integrations-guide/image/#formats) is not required, the original image format of remote images is unknown and will not be included by default. If not provided, only `webp` and `avif` will be included. + + +![Astro](https://example.com/images/remote-image.png) +``` -#### Local Images +The `` tag is not supported, nor is the `` component. -(required attributes: [`src`](/en/guides/integrations-guide/image/#src-1), [`widths`](/en/guides/integrations-guide/image/#widths), [`sizes`](/en/guides/integrations-guide/image/#sizes), [`alt`](/en/guides/integrations-guide/image/#alt-1)) +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. -Import your image in frontmatter and pass it directly to the `` component's `src` attribute. +## Images in MDX files -You must provide the component with guidance for image widths and screen sizes, but [all other properties](/en/guides/integrations-guide/image/#picture-) are optional. +You can use Astro's `` component and JSX `` tags in your `.mdx` files by importing both the component and your image. Use them just as they are [used in `.astro` files](#images-in-astro-files). -By default, the `` component's [`formats`](/en/guides/integrations-guide/image/#formats) will include `avif` and `webp` in addition to the image's original format if not specified. +Additionally, there is support for [standard Markdown `![alt](src)` syntax](#images-in-markdown-files) with no import required. -#### Images in `public/` +```mdx title="src/pages/post-1.mdx" +--- +title: My Page title +--- +import { Image } from 'astro:assets'; +import rocket from '~/assets/rocket.png'; -(required attributes: [`src`](/en/guides/integrations-guide/image/#src-1), [`widths`](/en/guides/integrations-guide/image/#widths), [`sizes`](/en/guides/integrations-guide/image/#sizes), [`alt`](/en/guides/integrations-guide/image/#alt-1), and [`aspectRatio`](/en/guides/integrations-guide/image/#aspectratio-1)) +# My MDX Page -Pass the component's `src` attribute a path relative to the public folder and include a value for `alt`. +// Local image stored in src/assets/ +A rocketship in space. +A rocketship in space. +![A rocketship in space](~/assets/rocket.png) -The image will be treated as a remote image, so a value for `aspectRatio` is also required to ensure the correct height can be calculated at build time. +// Image stored in public/images/ +A starry night sky. +A starry night sky. +![A starry night sky.](/images/stars.png) -You must provide the component with guidance for image widths and screen sizes, but [all other properties](/en/guides/integrations-guide/image/#picture-) are optional. -Although [`formats`](/en/guides/integrations-guide/image/#formats) is not required, the original image format of images in the `public/` folder is unknown and will not be included by default. If not provided, only `webp` and `avif` will be included. +// Remote image on another server + + +![Astro](https://example.com/images/remote-image.png) -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. +``` -#### Examples +## Images in UI framework components -```astro ---- -import { Picture } from '@astrojs/image/components'; -import localImage from '../assets/logo.png'; -const remoteImage = 'https://docs.astro.build/assets/full-logo-light.png'; ---- +When adding images in a UI framework component, use the framework's own image syntax to render an image (e.g. `` in JSX, `` in Svelte). - - +Local images must **first be imported** to access their properties, just as when [using the `` tag in `.astro` files](#img). - - +```jsx title="src/components/ReactImage.jsx" +import stars from "~/assets/stars.png" - - +export default function ReactImgage () { - - + return ( + A starry night sky. + ) +} +``` + +```svelte title="src/components/SvelteImage.svelte" + + +A starry night sky. ``` +### Passing the Image component -### Using in MDX +The `` component, like any other Astro component, is unavailable to UI framework components. -In `.mdx` files, `` and `` can receive your image `src` through imports and exports. +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): -```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 title="ImageWrapper.astro" +--- +import ReactComponent from './ReactComponent.jsx'; +import { Image } from "astro:assets" +import stars from "~/stars/docline.png"; +--- -Outer space. -Spaceship approaching the moon. - - + + A starry night sky. + ``` -### Setting Default Values +## Generating images with `getImage()` -Currently, there is no way to specify default values for all `` and `` components. Required attributes should be set on each individual component. +:::caution +`getImage()` relies on server-only APIs and breaks the build when used on the client. +::: -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: +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. -```astro title="src/components/BlogPostImage.astro" +`getImage()` takes an options object with the same properties as the Image component (except `alt`). + +```astro --- -import { Picture } from '@astrojs/image/components'; +import { getImage } from "astro:assets"; +import myBackground from "../background.png" -const {src, ...attrs} = Astro.props; +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) --- - - +
``` -### Using `` with the Image Integration +It returns an object with the following properties: -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 +```js { - src: string; - width: number; - height: number; - format: 'avif' | 'gif' | 'heic' | 'heif' | 'jpeg' | 'jpg' | 'png' | 'tiff' | 'webp'; + options: {...} // Original parameters passed, + src: "https//..." // Path to the generated image, + attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..) } ``` -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'; ---- -A rocketship in space. -``` - -Alternatively, add `?url` to your imports to tell them to return a source string. - -```astro "?url" ---- -import rocket from '../images/rocket.svg?url'; ---- -A rocketship in space. +## Using sharp - STILL WORKS LIKE THIS?? + +By default, Astro uses [Squoosh](https://github.com/GoogleChromeLabs/squoosh) to transform your images. This supports all JavaScript environments. + +If you're deploying to a Node environment, you may want to use [sharp](https://github.com/lovell/sharp), which offers faster performance but requires Node. To use sharp, first install it: + + + + ```shell + npm install sharp + ``` + + + ```shell + pnpm install sharp + ``` + + + ```shell + yarn add sharp + ``` + + + +Then, enable Astro's sharp image service in your config: + +```js title="astro.config.mjs" +import { defineConfig, sharpImageService } from "astro/config"; + +export default defineConfig({ + experimental: { + assets: true, + }, + image: { + service: sharpImageService(), + }, +}); ``` ## Using Images from a CMS or CDN -Image CDNs work with Astro. Use an image's full URL as the `src` attribute in an `` tag or Markdown notation. +Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. -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. - -To use [external images with the ``](#remote-images) and [``](#remote-images-1) components from Astro's image integration, you must specify the appropriate dimension and format values for working with remote images. +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 an `` tag with the appropriate `src` for you. ## 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. - ## 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. + diff --git a/src/i18n/en/nav.ts b/src/i18n/en/nav.ts index 0230197284921..089b71bd084ee 100644 --- a/src/i18n/en/nav.ts +++ b/src/i18n/en/nav.ts @@ -70,7 +70,7 @@ export default [ key: 'guides/client-side-scripts', }, { text: 'CSS & Styling', slug: 'guides/styling', key: 'guides/styling' }, - { text: 'Assets (Experimental)', slug: 'guides/assets', key: 'guides/assets' }, + { text: 'Assets (upgrade v3, reference?)', slug: 'guides/assets', key: 'guides/assets' }, { text: 'Images', slug: 'guides/images', key: 'guides/images' }, { text: 'Fonts', slug: 'guides/fonts', key: 'guides/fonts' }, { text: 'Imports', slug: 'guides/imports', key: 'guides/imports' }, From 4d85ed907d588845dfedf6e8396b6c4abe284098 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Mon, 17 Jul 2023 11:52:55 +0000 Subject: [PATCH 13/58] update assets folder guidance, and some formatting --- src/content/docs/en/guides/assets.mdx | 4 +- src/content/docs/en/guides/images.mdx | 85 ++++++++++++++------------- 2 files changed, 44 insertions(+), 45 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index f35393c34948e..dea5c66b00451 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -32,9 +32,7 @@ When you next run Astro, it will update your `src/env.d.ts` file to configure ty ### Move your images to `src/assets/` -Create `src/assets/`, which Astro will recognize as your new assets folder. - -We recommend storing all images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), you can put your images there and we promise we won't break them! But, images can be stored anywhere, including alongside your content, if you prefer. +If you create an `src/assets/` directory, Astro will will recognize this as an assets folder and provide a built-in `~/assets` alias for referencing your image files. This location is optional. If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), you can put your images there and we promise we won't break them! But, images can be stored anywhere, including alongside your content, if you prefer. Your images can be used by components (`.astro`, `.mdx`, and other UI frameworks) and in Markdown files. diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index a5232b79ebf24..abf4cbdda1837 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -18,11 +18,19 @@ We recommend that local images are kept in `src/` when possible so that Astro ca In Astro v3.0, your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Store your images in the `public/` folder only if you want to avoid any processing. -### `src/assets/` +### `src/assets/` vs colocated images -We recommend storing all local images to be optimized in the `src/assets/` directory to make use of our official `~/assets` alias, although this location is optional. +If you create an `src/assets/` directory, Astro will will recognize this as an assets folder and provide a built-in `~/assets` alias for referencing your image files. This location is optional. -If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), this folder ensures the greatest stability as we continue to build more asset features. But, images can be stored anywhere, including alongside your content, if you prefer. +If you don't know where to put your images, or if you're building a product around Astro (e.g. a CMS), this folder ensures the greatest stability as we continue to build more asset features. But, images can be stored anywhere, including alongside your content, if you prefer. Use relative file paths or [create your own import aliases](/en/guides/aliases/) to import or reference the image: + +```astro +--- +import asset from '~/assets/myAsset.jpg'; +import colocated from './myColocatedImage.avif'; +import anywhereIWant from '../../../images/myImageCanLiveAnywhere.png'; +--- +``` ### Remote images @@ -94,39 +102,39 @@ The format of the `src` value of your image file depends on where your image fil - **Local images in `src/`** - you must **also import the image** using a relative file path or [import alias](/en/guides/aliases/) such as the included `~/assets/` alias. Then use the import name as the `src` value: -```astro "myImportedImage" "{myImportedImage}" ---- -import { Image } from 'astro:assets'; -import myImportedImage from `~/assets/my-local-image.png` ---- -descriptive text -``` + ```astro "myImportedImage" "{myImportedImage}" + --- + import { Image } from 'astro:assets'; + import myImportedImage from `~/assets/my-local-image.png` + --- + descriptive text + ``` - **Images in the `public/` folder** - use the image's **file path relative to the public folder**: -```astro '"/images/my-public-image.png"' ---- -import { Image } from 'astro:assets'; ---- -descriptive text -``` + ```astro '"/images/my-public-image.png"' + --- + import { Image } from 'astro:assets'; + --- + descriptive text + ``` - **Remote images** - use the image's **full URL** as the property value: -```astro '"https://example.com/remote-image.jpg"' ---- -import { Image } from 'astro:assets'; ---- -descriptive text -``` + ```astro '"https://example.com/remote-image.jpg"' + --- + import { Image } from 'astro:assets'; + --- + descriptive text + ``` ##### alt (required) @@ -217,15 +225,15 @@ It accepts all HTML `` tag properties, and the only required property is `s Local images must be **imported from the relative path** from the existing `.astro` file, or use an [import alias](/en/guides/aliases/), such as the included `~/assets/` alias. Then, you can access the image's `src` and other properties to use in the `` tag. -```astro ".src" "img" +```astro "myCat.src" "myDog.src" --- // import local images import myCat from `~/assets/local-cat.png` import myDog from `../../images/pets/local-dog.jpg` --- // access the image properties -descriptive text -descriptive text +A sleeping cat. +A barking dog. ``` Imported image assets match the following signature: @@ -243,7 +251,7 @@ interface ImageMetadata { For images located within `public/` use the image's **file path relative to the public folder** as the `src` value: ```astro '"/images/public-cat.jpg"' -a sleeping cat +A sleeping cat. ``` #### Remote images @@ -251,14 +259,7 @@ For images located within `public/` use the image's **file path relative to the For remote images, use the image's **full URL** as the `src` value: ```astro '"https://example.com/remote-cat.jpg"' -a sleeping cat +A sleeping cat. ``` ### Choosing `` vs `` From 86cac5f0aea26c4e6021ac001c27dc3bc2dc3cb7 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Mon, 17 Jul 2023 14:26:33 +0000 Subject: [PATCH 14/58] 3 migration guides - update links to image resources. NEED TO CHECK ALL CODE SAMPLES FOR USAGE --- src/content/docs/en/guides/assets.mdx | 2 ++ .../guides/migrate-to-astro/from-gatsby.mdx | 21 +++++++++---------- .../guides/migrate-to-astro/from-nextjs.mdx | 11 +++++----- .../guides/migrate-to-astro/from-nuxtjs.mdx | 13 ++++++------ 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/src/content/docs/en/guides/assets.mdx b/src/content/docs/en/guides/assets.mdx index dea5c66b00451..5b41585824015 100644 --- a/src/content/docs/en/guides/assets.mdx +++ b/src/content/docs/en/guides/assets.mdx @@ -7,6 +7,8 @@ i18nReady: false ## v3 update guide stuff Assets may cause some breaking changes when you upgrade your Astro project to v3. +- `image.src` now require for `` tag +- can no longer use `` tag in `.md` files ### Update Config 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 83475c0f167c1..5bc080e21dfc3 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 @@ -321,30 +321,29 @@ See more about [Styling in Astro](/en/guides/styling/). ### Gatsby Image Plugin to Astro -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 `` tag as appropriate. ```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'; --- -The Astro Logo -A rocketship in space. +A rocketship in space. +A rocketship in space. ``` -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 component attributes](/en/guides/integrations-guide/image/#usage) available for these components, 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 to the relative URL. Using the HTML `` tag directy is not supported in `.md` files, and must be converted to Markdown syntax. ```md # My Markdown Page - -![A starry night sky.](/assets/stars.png) -A starry night sky. + +![A starry night sky.](~/assets/stars.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-nextjs.mdx b/src/content/docs/en/guides/migrate-to-astro/from-nextjs.mdx index beed148adb50b..7fce24d76d236 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 @@ -419,16 +419,15 @@ See more about [Styling in Astro](/en/guides/styling/). ### Next Image Plugin to Astro -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. +Convert any Next `` components to [Astro's own image component](/en/guides/images/#image--astroassets), or or to a standard HTML `` / JSX `` tag as appropriate. See a [full list of component attributes](/en/guides/images/#properties) available for Astro's `` component, 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'; --- -The Astro Logo -A rocketship in space. +A rocketship in space. +A rocketship in space. ``` 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 aa383fc9b3530..6c4bf41bbca44 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 @@ -489,18 +489,17 @@ See more about [Styling in Astro](/en/guides/styling/). ### Nuxt Image Plugin to Astro -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), or to a standard HTML `` or `` tag. -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. +See a [full list of component attributes](/en/guides/images/#properties) available for Astro's `` component, 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'; --- -The Astro Logo -A rocketship in space. +A rocketship in space. +A rocketship in space. ``` 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. From b6b8020579eb3f9c4d0e6c419a0568709e297398 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Mon, 17 Jul 2023 14:39:54 +0000 Subject: [PATCH 15/58] update link to public folder --- src/content/docs/en/core-concepts/astro-components.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/core-concepts/astro-components.mdx b/src/content/docs/en/core-concepts/astro-components.mdx index b25a7c3ec7b1a..7eea749e5145d 100644 --- a/src/content/docs/en/core-concepts/astro-components.mdx +++ b/src/content/docs/en/core-concepts/astro-components.mdx @@ -289,7 +289,7 @@ Astro supports importing and using `.html` files as components or placing these HTML components must contain only valid HTML, and therefore lack key Astro component features: - They don't support frontmatter, server-side imports, or dynamic expressions. - Any ` A starry night sky. @@ -569,7 +549,7 @@ Additionally, the HTML `` is no longer supported in `.md` files. Replace th # My Markdown Page -![A starry night sky.](~/assets/stars.png) +![A starry night sky.](../../assets/stars.png) A starry night sky. 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 eb7020c9828a6..868a21faec301 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 @@ -326,7 +326,7 @@ Convert Gatsby's `` and `` components to [Astro's ```astro title="src/pages/index.astro" --- import { Image } from 'astro:assets'; -import rocket from '~/assets/rocket.png'; +import rocket from '../assets/rocket.png'; --- A rocketship in space. A rocketship in space. @@ -342,7 +342,7 @@ To continue using [images in Markdown (`.md`) files](/en/guides/images/#images-i # My Markdown Page -![A starry night sky.](~/assets/stars.png) +![A starry night sky.](../assets/stars.png) ``` 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 317e38196da13..26ac903019539 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 @@ -424,7 +424,7 @@ Convert any Next `` components to [Astro's own image component](/en/gui ```astro title="src/pages/index.astro" --- import { Image } from 'astro:assets'; -import rocket from '~/assets/rocket.png'; +import rocket from '../assets/rocket.png'; --- A rocketship in space. A rocketship in space. 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 ddd9b7685a836..76e1a017812ac 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 @@ -496,7 +496,7 @@ See a [full list of component attributes](/en/guides/images/#properties) availab ```astro title="src/pages/index.astro" --- import { Image } from 'astro:assets'; -import rocket from '~/assets/rocket.png'; +import rocket from '../assets/rocket.png'; --- A rocketship in space. A rocketship in space. From 7b3b17bd800ead052f566c268be3fb9ace817c85 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 19:48:44 +0000 Subject: [PATCH 28/58] remove references to assets folder entirely --- src/content/docs/en/core-concepts/project-structure.mdx | 3 --- src/content/docs/en/guides/images.mdx | 2 +- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/content/docs/en/core-concepts/project-structure.mdx b/src/content/docs/en/core-concepts/project-structure.mdx index 40d612b4506ac..904be058be93f 100644 --- a/src/content/docs/en/core-concepts/project-structure.mdx +++ b/src/content/docs/en/core-concepts/project-structure.mdx @@ -66,9 +66,6 @@ Some files (like Astro components) are not even sent to the browser as written b While this guide describes some popular conventions used in the Astro community, the only directories reserved by Astro are `src/pages/` and `src/content/`. You are free to rename and reorganize any other directories in a way that works best for you. ::: -### `src/assets` - -The [`src/assets`](/en/guides/images/#srcassets-vs-colocated-images) directory is the recommended folder to use for storing assets (e.g. images) that are processed by Astro if you are grouping all your images together. This is not required, and this is not a special reserved folder. You can store your images anywhere, even alongside your content. ### `src/components` diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index e50e8dc77f1a2..074ef9033f7bb 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -511,7 +511,7 @@ If necessary, also update your `src/env.d.ts` file to replace the `astro/client- ### Decide where to store your images -See the Images guide to help you decide [where to store your images](/en/guides/images/#where-to-store-images), including whether you want to create and use the new, reserved `/assets/` folder. +See the Images guide to help you decide [where to store your images](/en/guides/images/#where-to-store-images).. ### Update existing `` tags From 0013e20505d941a2a9b4e2ab36789d9073752ae8 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 20:35:06 +0000 Subject: [PATCH 29/58] added info about remote images --- src/content/docs/en/guides/images.mdx | 37 ++++++++++++++++++++++++--- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 074ef9033f7bb..4d724ca478cc8 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -15,12 +15,14 @@ Astro provides several ways for you to use images on your site, whether they are We recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. Files in the `/public` directory are always served or copied into the build folder as-is, with no processing. -In Astro v3.0, your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Images can be stored in any folder, including alongside your content. Store your images in the `public/` folder only if you want to avoid any processing. +Your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Images can be stored in any folder, including alongside your content. Store your images in the `public/` folder only if you want to avoid any processing. ### Remote images You can also choose to store your images remotely, in a content management system (CMS) or digital asset management (DAM) platform. +For extra protection when dealing with external sources, remote images will only be processed from [authorized image sources](#authorizing-remote-images) specified in your configuration. However, any remote images can be displayed. + Astro can fetch your data remotely using APIs or display images from their full URL path. See our [CMS guides](/en/guides/cms/) for examples of integrating common services. @@ -44,9 +46,9 @@ import localBirdImage from ''../../images/subfolder/localBirdImage.png'; ### `` (`astro:assets`) -Use the built-in `` Astro component to display optimized versions of your local images. Remote images and images in the `public/` folder can also be used, but will not be processed. +Use the built-in `` Astro component to display optimized versions of your local images and [configured remote images](#authorizing-remote-images). Images in the `public/` folder, as well as remote images not specifically configured in your project can also be used with the Image component, but will not be processed. -`` can transform a local image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. +`` can transform a local or remote image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. :::tip[What is Cumulative Layout Shift?] [Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. @@ -255,9 +257,36 @@ Use the HTML `` element when you cannot use the `` component, for - when you do not want your image optimized by Astro - to access and change the `src` attribute dynamically client-side + +### Authorizing remote images + +You can configure lists of authorized image source URL domains and patterns for image optimization using [`image.domains`](/en/reference/configuration-reference/#imagedomain) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns). This configuration is an extra layer of safety to protect your site when showing images from an external source. No other remote images will 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"], + } +}); +``` + +The following configuration will only allow remote images from HTTPS hosts: + +```ts +// astro.config.mjs +export default defineConfig({ + image: { + remotePatterns: [{ protocol: "https" }], + } +}); +``` + ## Using Images from a CMS or CDN -Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. +Image CDNs work with all Astro image options. Use an image's full URL as the `src` attribute in the `` component, an `` tag, or in Markdown notation. For image optimization with remote images, also [configure your authorized domains or URL patterns](#authorizing-remote-images). 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 an `` tag with the appropriate `src` for you. From effcfa7aa3cfc5f2796163c37cd25d02c910e99a Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 21:39:24 +0000 Subject: [PATCH 30/58] next pass at new image page (upgrade stuff still to do) --- src/content/docs/en/guides/images.mdx | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 4d724ca478cc8..de1a9d5d3e85e 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -15,7 +15,9 @@ Astro provides several ways for you to use images on your site, whether they are We recommend that local images are kept in `src/` when possible so that Astro can transform, optimize and bundle them. Files in the `/public` directory are always served or copied into the build folder as-is, with no processing. -Your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Images can be stored in any folder, including alongside your content. Store your images in the `public/` folder only if you want to avoid any processing. +Your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc` and other UI frameworks. Images can be stored in any folder, including alongside your content. + +Store your images in the `public/` folder only if you want to avoid any processing. ### Remote images @@ -28,7 +30,9 @@ Astro can fetch your data remotely using APIs or display images from their full ## Images in `.astro` files -In `.astro` files, local images must be imported before they can be used. Import and use Astro's built-in `` component for optimized images. Alternatively, Astro syntax supports writing an HTML `` tag directly. +In `.astro` files, local images must be imported into the file in order to be used. Remote and `public/` images do not require importing. + +Import and use Astro's built-in `` component for optimized images. Alternatively, Astro syntax supports writing an HTML `` tag directly. ```astro title="src/pages/blog/MyImages.astro" --- @@ -46,9 +50,11 @@ import localBirdImage from ''../../images/subfolder/localBirdImage.png'; ### `` (`astro:assets`) -Use the built-in `` Astro component to display optimized versions of your local images and [configured remote images](#authorizing-remote-images). Images in the `public/` folder, as well as remote images not specifically configured in your project can also be used with the Image component, but will not be processed. +Use the built-in `` Astro component to display optimized versions of your local images and [configured remote images](#authorizing-remote-images). -`` can transform a local or remote image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. +Images in the `public/` folder, as well as remote images not specifically configured in your project can also be used with the Image component, but will not be processed. + +`` can transform a local or authorized remote image's dimensions, file type, and quality to produce an optimized `` tag to avoid **Cumulative Layout Shift (CLS)**. :::tip[What is Cumulative Layout Shift?] [Cumulative Layout Shift (CLS)](https://web.dev/cls/) is a Core Web Vital metric for measuring how much content shifted on your page during loading. The `` component optimizes for CLS by automatically selecting the correct `width` and `height` for your local images. @@ -136,7 +142,7 @@ These properties define the dimensions to use for the image. When using local images in their original aspect ratio, the `width` and `height` can be automatically inferred from the source file and are optional. -However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files to determine them. These images will not be optimized. +However, both of these properties are required for remote images and images stored in your `public/` folder as Astro is unable to analyze these files. ##### format @@ -260,7 +266,9 @@ Use the HTML `` element when you cannot use the `` component, for ### Authorizing remote images -You can configure lists of authorized image source URL domains and patterns for image optimization using [`image.domains`](/en/reference/configuration-reference/#imagedomain) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns). This configuration is an extra layer of safety to protect your site when showing images from an external source. No other remote images will be optimized, but using the `` component for these images will prevent Cumulative Layout Shift (CLS). +You can configure lists of authorized image source URL domains and patterns for image optimization using [`image.domains`](/en/reference/configuration-reference/#imagedomain) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns). This configuration is an extra layer of safety to protect your site when showing images from an external source. + +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: @@ -292,7 +300,7 @@ Alternatively, if the CDN provides a Node.js SDK, you can use that in your proje ## Images in Markdown files -Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's Image Services API to optimize your local images. +Use standard Markdown `![alt](src)` syntax in your `.md` files. This syntax works with Astro's Image Services API to optimize your local images and authorized remote images. ```md @@ -459,7 +467,7 @@ import stars from "~/stars/docline.png"; 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. -`getImage()` takes an options object with the same properties as the Image component (except `alt`). +`getImage()` takes an options object with the [same properties as the Image component](#properties) (except `alt`). ```astro --- From d4bdf1a4517d4d79012d7b40b32bc6f68b4b67d4 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 22:49:58 +0000 Subject: [PATCH 31/58] address links, incl fake config-ref links --- src/content/docs/en/guides/images.mdx | 2 +- .../docs/en/guides/migrate-to-astro/from-gatsby.mdx | 4 ++-- src/content/docs/en/reference/configuration-reference.mdx | 7 +++++++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index de1a9d5d3e85e..92aee12ad1098 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -266,7 +266,7 @@ Use the HTML `` element when you cannot use the `` component, for ### Authorizing remote images -You can configure lists of authorized image source URL domains and patterns for image optimization using [`image.domains`](/en/reference/configuration-reference/#imagedomain) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns). This configuration is an extra layer of safety to protect your site when showing images from an external source. +You can configure lists of authorized image source URL domains and patterns for image optimization using [`image.domains`](/en/reference/configuration-reference/#imagedomains) and [`image.remotePatterns`](/en/reference/configuration-reference/#imageremotepatterns). This configuration is an extra layer of safety to protect your site when showing images from an external source. Remote images from other sources will not be optimized, but using the `` component for these images will prevent Cumulative Layout Shift (CLS). 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 868a21faec301..c934e2854fa1b 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 @@ -332,9 +332,9 @@ import rocket from '../assets/rocket.png'; A rocketship in space. ``` -Astro's `` component works 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 component attributes](/en/guides/images/#properties) available for this component, and note that several will differ from Gatsby's attributes. -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 to the relative URL. Using the HTML `` tag directy is not supported in `.md` files, and must be converted to Markdown syntax. +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, and must be converted to Markdown syntax. ```md diff --git a/src/content/docs/en/reference/configuration-reference.mdx b/src/content/docs/en/reference/configuration-reference.mdx index bb3b5f3c5280e..281436d2f76fb 100644 --- a/src/content/docs/en/reference/configuration-reference.mdx +++ b/src/content/docs/en/reference/configuration-reference.mdx @@ -660,6 +660,13 @@ The service entrypoint can be either one of the included services, or a third-pa } ``` +### image.domains + +Placeholder until merged from Astro repository + +### image.remotePatterns + +Placeholder until merged from Astro repository ## Markdown Options From 26279ba2a0e04d5e016cf76261c4f1dad3be0bd2 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 22:52:05 +0000 Subject: [PATCH 32/58] another quick link hotfix in error message --- .../docs/en/reference/errors/missing-image-dimension.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/content/docs/en/reference/errors/missing-image-dimension.mdx b/src/content/docs/en/reference/errors/missing-image-dimension.mdx index 1359f4161821e..be637d2e64d36 100644 --- a/src/content/docs/en/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/en/reference/errors/missing-image-dimension.mdx @@ -22,6 +22,6 @@ If your image is inside your `src` folder, you probably meant to import it inste **See Also:** - [Assets (Experimental)](/en/guides/images/) -- [Image component#width-and-height](/en/guides/images/#width-and-height) +- [Image component#width-and-height](/en/guides/images/#width-and-height-required-for-public-and-remote-images) From 9e4b4aab196b0f9b76761cdd293b7696e2940c8d Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 22:59:08 +0000 Subject: [PATCH 33/58] change remaining links to images; incl eggregious error message hotfixes --- src/content/docs/de/guides/images.mdx | 8 ++++---- src/content/docs/es/core-concepts/project-structure.mdx | 2 +- src/content/docs/es/guides/images.mdx | 4 ++-- .../docs/es/guides/migrate-to-astro/from-gatsby.mdx | 2 +- .../docs/es/guides/migrate-to-astro/from-nextjs.mdx | 2 +- .../docs/es/guides/migrate-to-astro/from-nuxtjs.mdx | 2 +- .../docs/es/reference/errors/expected-image-options.mdx | 2 +- src/content/docs/es/reference/errors/expected-image.mdx | 2 +- .../docs/es/reference/errors/image-missing-alt.mdx | 5 ++--- .../docs/es/reference/errors/local-image-used-wrongly.mdx | 2 +- .../docs/es/reference/errors/markdown-image-not-found.mdx | 2 +- .../docs/es/reference/errors/missing-image-dimension.mdx | 4 ++-- src/content/docs/es/reference/image-service-reference.mdx | 2 +- src/content/docs/ja/guides/images.mdx | 8 ++++---- src/content/docs/ko/core-concepts/project-structure.mdx | 2 +- .../docs/pt-br/core-concepts/project-structure.mdx | 2 +- src/content/docs/pt-br/guides/images.mdx | 8 ++++---- .../pt-br/reference/errors/expected-image-options.mdx | 2 +- .../docs/pt-br/reference/errors/expected-image.mdx | 2 +- .../docs/pt-br/reference/errors/image-missing-alt.mdx | 5 ++--- .../pt-br/reference/errors/markdown-image-not-found.mdx | 2 +- .../pt-br/reference/errors/missing-image-dimension.mdx | 4 ++-- .../docs/zh-cn/core-concepts/project-structure.mdx | 2 +- src/content/docs/zh-cn/guides/images.mdx | 8 ++++---- .../docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx | 2 +- .../docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx | 2 +- .../docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx | 2 +- .../zh-cn/reference/errors/expected-image-options.mdx | 2 +- .../docs/zh-cn/reference/errors/expected-image.mdx | 2 +- .../docs/zh-cn/reference/errors/image-missing-alt.mdx | 5 ++--- .../zh-cn/reference/errors/local-image-used-wrongly.mdx | 2 +- .../zh-cn/reference/errors/markdown-image-not-found.mdx | 2 +- .../zh-cn/reference/errors/missing-image-dimension.mdx | 4 ++-- .../docs/zh-cn/reference/image-service-reference.mdx | 2 +- 34 files changed, 53 insertions(+), 56 deletions(-) diff --git a/src/content/docs/de/guides/images.mdx b/src/content/docs/de/guides/images.mdx index e561b6b44b20c..693194dc9210e 100644 --- a/src/content/docs/de/guides/images.mdx +++ b/src/content/docs/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/es/core-concepts/project-structure.mdx b/src/content/docs/es/core-concepts/project-structure.mdx index abe6b9d88fdc2..3d196c818c84c 100644 --- a/src/content/docs/es/core-concepts/project-structure.mdx +++ b/src/content/docs/es/core-concepts/project-structure.mdx @@ -67,7 +67,7 @@ Mientras esta guía describe algunas convenciones populares utilizadas en la com ### `src/assets` -El directorio [`src/assets`](/es/guides/assets/) es la carpeta recomendada para almacenar activos (p. ej, imágenes) que son procesados por Astro. Esto no es obligatorio y no es una carpeta especial reservada. +El directorio [`src/assets`](/es/guides/images/) es la carpeta recomendada para almacenar activos (p. ej, imágenes) que son procesados por Astro. Esto no es obligatorio y no es una carpeta especial reservada. ### `src/components` diff --git a/src/content/docs/es/guides/images.mdx b/src/content/docs/es/guides/images.mdx index 3a84c076fb327..f366d3d1ba39d 100644 --- a/src/content/docs/es/guides/images.mdx +++ b/src/content/docs/es/guides/images.mdx @@ -12,7 +12,7 @@ import Since from '~/components/Since.astro'; :::note[`astro:assets` (Experimental - en camino para la versión v3.0)] El modulo experimental `astro:assets` estará habilitado por defecto en `astro@3.0`. -¡Sigue la [Guía de Assets (Experimental)](/es/guides/assets/) para comenzar a usar la nueva solución de imágenes de Astro hoy mismo! +¡Sigue la [Guía de Assets (Experimental)](/es/guides/images/) para comenzar a usar la nueva solución de imágenes de Astro hoy mismo! **Algunos de los consejos a continuación son incompatibles con la bandera experimental. Consulta la página de Assets si estás usando `astro:assets`.** ::: @@ -129,7 +129,7 @@ La integración [`@astrojs/image`](https://github.com/withastro/astro/tree/main/ Te sugerimos que la elimines lo antes posible y que uses el módulo experimental `astro:assets` que se integrará en `astro@3.0`. -¡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! +¡Sigue la [Guía de Assets (experimental)](/es/guides/images/) para empezar a usar la nueva solución de imágenes de Astro hoy mismo! **`astro:assets` no es un reemplazo completo de `@astrojs/image` en este momento, pero está en desarrollo activo.** ::: 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 4dbabb9a02fa6..9e4b37c77e956 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 @@ -324,7 +324,7 @@ Ver más sobre [Estilizando en Astro](/es/guides/styling/). :::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. +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/images/) 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. 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 feee1e40b6d4a..899b1ccbfd2ba 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 @@ -423,7 +423,7 @@ Ver más acerca de [Estilos en Astro](/es/guides/styling/). :::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. +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/images/) como solución de imagen. ::: 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. 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 0fa785ba45db4..377a159fe2cd0 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 @@ -516,7 +516,7 @@ Ve más sobre [Estilos en Astro](/es/guides/styling/). :::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. +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/images/) 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. diff --git a/src/content/docs/es/reference/errors/expected-image-options.mdx b/src/content/docs/es/reference/errors/expected-image-options.mdx index a6f0b35d75606..db3d96e895b35 100644 --- a/src/content/docs/es/reference/errors/expected-image-options.mdx +++ b/src/content/docs/es/reference/errors/expected-image-options.mdx @@ -19,4 +19,4 @@ const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); En la mayoría de los casos, este error se produce porque los parámetros se han pasado directamente en lugar de dentro de un objeto. **Ver también:** -- [Assets (Experimental)](/es/guides/assets/) +- [Assets (Experimental)](/es/guides/images/) diff --git a/src/content/docs/es/reference/errors/expected-image.mdx b/src/content/docs/es/reference/errors/expected-image.mdx index b3f3d846cb84f..72e8c9a52a651 100644 --- a/src/content/docs/es/reference/errors/expected-image.mdx +++ b/src/content/docs/es/reference/errors/expected-image.mdx @@ -22,4 +22,4 @@ import myImage from "../assets/my_image.png"; En la mayoría de los casos, este error ocurre cuando el valor pasado a `src` es undefined. **Ver también:** -- [Assets (Experimental)](/es/guides/assets/) +- [Assets (Experimental)](/es/guides/images/) diff --git a/src/content/docs/es/reference/errors/image-missing-alt.mdx b/src/content/docs/es/reference/errors/image-missing-alt.mdx index a6c803364c79d..dfcda9fb19940 100644 --- a/src/content/docs/es/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/es/reference/errors/image-missing-alt.mdx @@ -17,6 +17,5 @@ La propiedad `alt` te permite proporcionar texto alternativo descriptivo a los u 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 ignorar la imagen. **Ver también:** -- [Activos (experimental)](/es/guides/assets/) -- [Componente Imagen](/es/guides/assets/#image--astroassets) -- [Componente Imagen#alt](/es/guides/assets/#alt-required) +- [Activos (experimental)](/es/guides/images/) + diff --git a/src/content/docs/es/reference/errors/local-image-used-wrongly.mdx b/src/content/docs/es/reference/errors/local-image-used-wrongly.mdx index 2b508c558c7b6..897e747974f92 100644 --- a/src/content/docs/es/reference/errors/local-image-used-wrongly.mdx +++ b/src/content/docs/es/reference/errors/local-image-used-wrongly.mdx @@ -23,4 +23,4 @@ import myImage from "../my_image.png"; ``` **Ver también:** -- [Assets (Experimental)](/es/guides/assets/) +- [Assets (Experimental)](/es/guides/images/) diff --git a/src/content/docs/es/reference/errors/markdown-image-not-found.mdx b/src/content/docs/es/reference/errors/markdown-image-not-found.mdx index 146db4912eace..558982682e739 100644 --- a/src/content/docs/es/reference/errors/markdown-image-not-found.mdx +++ b/src/content/docs/es/reference/errors/markdown-image-not-found.mdx @@ -12,4 +12,4 @@ Astro no pudo encontrar una imagen que incluiste en tu contenido Markdown. Norma Las imágenes en Markdown son relativas al archivo actual. Para referirse a una imagen que se encuentra en la misma carpeta que el archivo `.md`, la ruta debe empezar por `./`. **Ver también:** -- [Assets (Experimental)](/es/guides/assets/) +- [Assets (Experimental)](/es/guides/images/) diff --git a/src/content/docs/es/reference/errors/missing-image-dimension.mdx b/src/content/docs/es/reference/errors/missing-image-dimension.mdx index 39423814b18b1..0d814a56e3324 100644 --- a/src/content/docs/es/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/es/reference/errors/missing-image-dimension.mdx @@ -17,5 +17,5 @@ Para imágenes remotas, no se pueden inferir `width` y `height` del archivo orig Si tu imagen está dentro de tu carpeta `src`, probablemente quieras importarla en su lugar. Consulta [la guía de importaciones para obtener más información](/es/guides/imports/#otros-recursos). **Ver también:** -- [Activos (experimental)](/es/guides/assets/) -- [Componente Imagen#width-and-height](/es/guides/assets/#width-and-height) +- [Activos (experimental)](/es/guides/images/) + diff --git a/src/content/docs/es/reference/image-service-reference.mdx b/src/content/docs/es/reference/image-service-reference.mdx index 97eb465df3093..5109f610703ba 100644 --- a/src/content/docs/es/reference/image-service-reference.mdx +++ b/src/content/docs/es/reference/image-service-reference.mdx @@ -3,7 +3,7 @@ title: API de Servicio de Imágenes i18nReady: true --- -Los [assets](/es/guides/assets/) de Astro fueron diseñados para facilitar que cualquier servicio de optimización de imágenes construya un servicio sobre Astro. +Los [assets](/es/guides/images/) de Astro fueron diseñados para facilitar que cualquier servicio de optimización de imágenes construya un servicio sobre Astro. :::caution La API de Servicios de Imágenes es una característica experimental de Astro introducida en la versión 2.1. Esta API está sujeta a cambios antes de que se marque como estable. diff --git a/src/content/docs/ja/guides/images.mdx b/src/content/docs/ja/guides/images.mdx index 185b4031ba8f0..54c53602c96e2 100644 --- a/src/content/docs/ja/guides/images.mdx +++ b/src/content/docs/ja/guides/images.mdx @@ -8,7 +8,7 @@ import Since from '~/components/Since.astro'; Astroは、プロジェクト内に保存されている画像やリモート上にリンクされている画像、CMSやCDNに保存されている画像をサイト上で表示するために様々な手段を提供しています。 :::note[アセットの活用 (実験的)] -実験的なアセットサポートが`astro@2.1.0`に追加されました。アセットサポートを有効にした場合、追加情報については [アセット (実験的) ガイド](/ja/guides/assets/) を参照してください。 +実験的なアセットサポートが`astro@2.1.0`に追加されました。アセットサポートを有効にした場合、追加情報については [アセット (実験的) ガイド](/ja/guides/images/) を参照してください。 **以下のアドバイスの中には、アセットのフラグを有効にした場合に互換性がなくなるものもあります。** ::: @@ -38,7 +38,7 @@ import rocket from '../images/rocket.svg'; `.md`ファイル内では標準的な`![]()`構文や``タグを記載することで`public/`フォルダや、他サーバー上にあるリモート画像を表示できます。 -もし`public/`に画像を保存できない場合、[アセットの実験的なサポート](/ja/guides/assets/)を有効にするか、インポートされたコンポーネントをMarkdownのような構文と組み合わせて使える`.mdx`ファイルフォーマットを利用することをお勧めします。AstroにMDXのサポートを追加するには[MDX インテグレーション](/ja/guides/integrations-guide/mdx/)を利用します。 +もし`public/`に画像を保存できない場合、[アセットの実験的なサポート](/ja/guides/images/)を有効にするか、インポートされたコンポーネントをMarkdownのような構文と組み合わせて使える`.mdx`ファイルフォーマットを利用することをお勧めします。AstroにMDXのサポートを追加するには[MDX インテグレーション](/ja/guides/integrations-guide/mdx/)を利用します。 ```md @@ -120,7 +120,7 @@ import logo from '../images/logo.png'; ### `src/assets/` (実験的) -`/assets/` フォルダの実験的な使用を有効にするには、[アセット(実験的)](/ja/guides/assets/)ガイドを参照してください。 +`/assets/` フォルダの実験的な使用を有効にするには、[アセット(実験的)](/ja/guides/images/)ガイドを参照してください。 その場合、既存の画像を更新し、現在のAstro画像インテグレーションを削除する必要があります。また、Astroの新機能の一部を利用するためには、さらに手動での変更が必要になります。 @@ -131,7 +131,7 @@ Astro公式の画像のインテグレーションは、最適化された画像 [`@astrojs/image`のインストール](/ja/guides/integrations-guide/image/#installation)で、`.astro`と`.mdx`などのAstroコンポーネントを利用できるファイル内でこの2つのコンポーネントを利用できます。 :::note[アセットの互換性がない] -アセットの実験的なサポートを有効にしている場合は、公式インテグレーションをアンインストールする必要があります。詳細については、[アセット (実験的) ガイド](/ja/guides/assets/) を参照してください。 +アセットの実験的なサポートを有効にしている場合は、公式インテグレーションをアンインストールする必要があります。詳細については、[アセット (実験的) ガイド](/ja/guides/images/) を参照してください。 ::: ### `` diff --git a/src/content/docs/ko/core-concepts/project-structure.mdx b/src/content/docs/ko/core-concepts/project-structure.mdx index 9890b45a76cb9..7009ff547bb91 100644 --- a/src/content/docs/ko/core-concepts/project-structure.mdx +++ b/src/content/docs/ko/core-concepts/project-structure.mdx @@ -64,7 +64,7 @@ Astro는 `src/`에 있는 파일을 처리하고, 최적화하고, 번들링하 ### `src/assets` -[`src/assets/`](/ko/guides/assets/) 디렉터리는 Astro에서 처리하는 에셋(이미지 등)을 저장하는 데 사용할 권장 폴더입니다. 이 폴더는 필수는 아니며 특별한 예약 폴더도 아닙니다. +[`src/assets/`](/ko/guides/images/) 디렉터리는 Astro에서 처리하는 에셋(이미지 등)을 저장하는 데 사용할 권장 폴더입니다. 이 폴더는 필수는 아니며 특별한 예약 폴더도 아닙니다. ### `src/components` diff --git a/src/content/docs/pt-br/core-concepts/project-structure.mdx b/src/content/docs/pt-br/core-concepts/project-structure.mdx index 27ef7e458b90d..3939fce19256e 100644 --- a/src/content/docs/pt-br/core-concepts/project-structure.mdx +++ b/src/content/docs/pt-br/core-concepts/project-structure.mdx @@ -68,7 +68,7 @@ Enquanto esse guia descreve algumas convenções populares usadas na comunidade ### `src/assets` -A pasta [`src/assets`](/pt-br/guides/assets/) é a pasta recomendada para armazenar assets (e.x. imagens) a serem processados pelo Astro. Isso não é obrigatório, e esta não é uma pasta especial reservada. +A pasta [`src/assets`](/pt-br/guides/images/) é a pasta recomendada para armazenar assets (e.x. imagens) a serem processados pelo Astro. Isso não é obrigatório, e esta não é uma pasta especial reservada. ### `src/components` diff --git a/src/content/docs/pt-br/guides/images.mdx b/src/content/docs/pt-br/guides/images.mdx index 32a4d2bc18d9d..0a62e008a01cb 100644 --- a/src/content/docs/pt-br/guides/images.mdx +++ b/src/content/docs/pt-br/guides/images.mdx @@ -11,7 +11,7 @@ Astro providencia diversas formas de você utilizar imagens em seu site, estejam :::note[`astro:assets` (Experimental - chegando em v3.0)] O módulo experimental `astro:assets` vai ser habilitado por padrão em `astro@3.0`. -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! +Siga o [Guia de Assets (Experimental)](/pt-br/guides/images/) para começar a usar a nova solução de imagens do Astro hoje mesmo! **Algumas das recomendações abaixo são incompatíveis com a flag experimental. Por favor veja a página de Assets se você estiver usando `astro:assets`.** ::: @@ -40,7 +40,7 @@ import foguete from '../imagens/foguete.svg'; 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. -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. +Se você não consegue manter suas imagens em `public/`, nós recomendamos habilitar o [suporte experimental para assets](/pt-br/guides/images/), 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. ```md @@ -123,7 +123,7 @@ O atributo `src` é **relativo ao diretório public**. No Markdown, você pode t ### `src/assets/` (experimental) -Veja o guia [Assets (Experimental)](/pt-br/guides/assets/) para habilitar o uso experimental da pasta `/assets/`. +Veja o guia [Assets (Experimental)](/pt-br/guides/images/) para habilitar o uso experimental da pasta `/assets/`. 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. @@ -134,7 +134,7 @@ A integração [`@astrojs/image`](https://github.com/withastro/astro/tree/main/p Nós sugerimos remover ela assim que for conveniente e utilizar o módulo experimental `astro:assets` que fará parte do `astro@3.0`. -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! +Siga o [Guia de Assets (Experimental)](/pt-br/guides/images/) para começar a usar a nova solução de imagens do Astro hoje mesmo! **`astro:assets` não é um substituto completo do `@astrojs/image` nesse momento, mas está sob constante desenvolvimento.** ::: diff --git a/src/content/docs/pt-br/reference/errors/expected-image-options.mdx b/src/content/docs/pt-br/reference/errors/expected-image-options.mdx index f6683ef8f12af..5c273015115e7 100644 --- a/src/content/docs/pt-br/reference/errors/expected-image-options.mdx +++ b/src/content/docs/pt-br/reference/errors/expected-image-options.mdx @@ -20,4 +20,4 @@ const imagemOtimizada = await getImage({src: minhaImagem, width: 300, height: 30 Na maioria dos casos, este erro acontece pois os parâmetros foram passados diretamente, ao invés de dentro de um objeto. **Veja Também:** -- [Assets (Experimental)](/pt-br/guides/assets/) +- [Assets (Experimental)](/pt-br/guides/images/) diff --git a/src/content/docs/pt-br/reference/errors/expected-image.mdx b/src/content/docs/pt-br/reference/errors/expected-image.mdx index 5b6c48b23d15b..e39a28f1e70d3 100644 --- a/src/content/docs/pt-br/reference/errors/expected-image.mdx +++ b/src/content/docs/pt-br/reference/errors/expected-image.mdx @@ -23,4 +23,4 @@ import minhaImagem from "../assets/minha_imagem.png"; Na maioria dos casos, este erro acontece quando o valor passado a `src` é undefined. **Veja Também:** -- [Assets (Experimental)](/pt-br/guides/assets/) +- [Assets (Experimental)](/pt-br/guides/images/) diff --git a/src/content/docs/pt-br/reference/errors/image-missing-alt.mdx b/src/content/docs/pt-br/reference/errors/image-missing-alt.mdx index 49065c936156c..6d7af74cd8371 100644 --- a/src/content/docs/pt-br/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/pt-br/reference/errors/image-missing-alt.mdx @@ -13,6 +13,5 @@ A propriedade `alt` permite que você providencie texto alternativo descritivo p Se a imagem é meramente decorativa (isto é, não contribui para a compreensão da página), defina `alt=""` para que leitores de tela consigam ignorar a imagem. **Veja Também:** -- [Assets (Experimental)](/pt-br/guides/assets/) -- [Componente Image](/pt-br/guides/assets/#image--astroassets) --  [Componente Image#alt](/pt-br/guides/assets/#alt-required) +- [Assets (Experimental)](/pt-br/guides/images/) + diff --git a/src/content/docs/pt-br/reference/errors/markdown-image-not-found.mdx b/src/content/docs/pt-br/reference/errors/markdown-image-not-found.mdx index 5c298487ff0a0..54f638fba84ea 100644 --- a/src/content/docs/pt-br/reference/errors/markdown-image-not-found.mdx +++ b/src/content/docs/pt-br/reference/errors/markdown-image-not-found.mdx @@ -13,4 +13,4 @@ Astro não foi capaz de encontrar uma imagem que você incluiu no seu conteúdo Imagens no Markdown são relativas ao arquivo atual. Para se referir a uma imagem que não está localizada na mesma pastas que o arquivo `.md`, o caminho deve começar com `./` **Veja Também:** -- [Assets (Experimental)](/pt-br/guides/assets/) +- [Assets (Experimental)](/pt-br/guides/images/) diff --git a/src/content/docs/pt-br/reference/errors/missing-image-dimension.mdx b/src/content/docs/pt-br/reference/errors/missing-image-dimension.mdx index ac6785d86f181..bc31d8f0df83a 100644 --- a/src/content/docs/pt-br/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/pt-br/reference/errors/missing-image-dimension.mdx @@ -13,5 +13,5 @@ Para imagens remotas, `width` e `height` não podem ser inferidos a partir do ar Se sua imagem está dentro do seu diretório `src`, você provavelmente quis importá-lo no lugar. Veja [o guia de Importações para mais informações](/pt-br/guides/imports/#outros-assets). **Veja Também:** -- [Assets (Experimental)](/pt-br/guides/assets/) -- [Componente Image#width-e-height](/pt-br/guides/assets/#width-and-height) +- [Assets (Experimental)](/pt-br/guides/images/) + diff --git a/src/content/docs/zh-cn/core-concepts/project-structure.mdx b/src/content/docs/zh-cn/core-concepts/project-structure.mdx index 81c5b70e9b1d2..bdfb9a6ecac24 100644 --- a/src/content/docs/zh-cn/core-concepts/project-structure.mdx +++ b/src/content/docs/zh-cn/core-concepts/project-structure.mdx @@ -68,7 +68,7 @@ Astro 处理、压缩和打包你的 `src/` 文件以创建最终传递到浏览 ### `src/assets` -[`src/assets`](/zh-cn/guides/assets/) 目录推荐用于存储由 Astro 处理的资源(例如:图片)。这不是必需的,也不是特殊的保留文件夹。 +[`src/assets`](/zh-cn/guides/images/) 目录推荐用于存储由 Astro 处理的资源(例如:图片)。这不是必需的,也不是特殊的保留文件夹。 ### `src/components` diff --git a/src/content/docs/zh-cn/guides/images.mdx b/src/content/docs/zh-cn/guides/images.mdx index 837148a76ff97..b315d13e89864 100644 --- a/src/content/docs/zh-cn/guides/images.mdx +++ b/src/content/docs/zh-cn/guides/images.mdx @@ -11,7 +11,7 @@ import Since from '~/components/Since.astro'; :::note[`astro:assets` (Experimental - coming in v3.0)] 实验性 `astro:assets` 模块将在 `astro@3.0` 中默认启用. -请按照 [资源(实验性)使用指南](/zh-cn/guides/assets/) 开始使用新的图片解决方案! +请按照 [资源(实验性)使用指南](/zh-cn/guides/images/) 开始使用新的图片解决方案! **下面的一些建议可能与实验性标志不兼容。如果你正在使用 `astro:assets` 请参考资源页面。** ::: @@ -41,7 +41,7 @@ import rocket from '../images/rocket.svg'; 可以在 `.md` 文件中使用 Markdown 标准语法 `![]()`,或 HTML 标准语法 `` 标签,来调用位于 `public/` 文件夹下或其它服务器上的图片。 -如果你无法将图片保留在 `public/` 中,我们建议启用 [资源的实验性支持](/zh-cn/guides/assets/), 或使用 `.mdx` 文件格式,该格式允许你将导入的组件与类似 Markdown 的语法结合起来。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 向 Astro 添加对 MDX 的支持。 +如果你无法将图片保留在 `public/` 中,我们建议启用 [资源的实验性支持](/zh-cn/guides/images/), 或使用 `.mdx` 文件格式,该格式允许你将导入的组件与类似 Markdown 的语法结合起来。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 向 Astro 添加对 MDX 的支持。 ```md @@ -126,7 +126,7 @@ import logo from '../images/logo.png'; ### `src/assets/` (实验性) -请参阅 [资源(实验性)](/zh-cn/guides/assets/) 指南,了解如何启用 `/assets/` 文件夹的实验性用法。 +请参阅 [资源(实验性)](/zh-cn/guides/images/) 指南,了解如何启用 `/assets/` 文件夹的实验性用法。 这将需要你更新现有图片,删除当前的 Astro 图片集成,并且还需要额外的手动更改以利用其某些新功能。 @@ -137,7 +137,7 @@ Astro v3 将不再主动支持 [`@astrojs/image`](https://github.com/withastro/a 我们建议你尽早删除它,并使用将内置在 `astro@3.0` 中的实验性 `astro:assets` 模块。 -请按照 [资源(实验性)使用指南](/zh-cn/guides/assets/) 开始使用新的图片解决方案! +请按照 [资源(实验性)使用指南](/zh-cn/guides/images/) 开始使用新的图片解决方案! **`astro:assets` 目前还不能完全替代 `@astrojs/image` ,但它正在被积极开发中。** ::: diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx index 09d420e54393c..84ef3ecdb2641 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx @@ -323,7 +323,7 @@ Gatsby 中使用 `gatsby-browser.js` 中的 CSS 导入实现全局样式。在 A :::note Astro v3.0 将包含一个新的 `astro:assets` 模块,并将弃用现有的 `@astrojs/image` 集成。 -目前已经可以通过实验性标志访问 `astro:assets`,并且这是开始新 Astro 项目的推荐方式。如果你正在迁移到 Astro pre-v3.0,我们建议[启用实验标志来使用资产](/zh-cn/guides/assets/)作为图像解决方案。 +目前已经可以通过实验性标志访问 `astro:assets`,并且这是开始新 Astro 项目的推荐方式。如果你正在迁移到 Astro pre-v3.0,我们建议[启用实验标志来使用资产](/zh-cn/guides/images/)作为图像解决方案。 ::: 将 Gatsby 的 `` 和 `` 组件与 [Astro 自己的图像集成组件](/zh-cn/guides/images/#astro-的图片集成) 或适当的标准 HTML `` / JSX `` 标签相互转换。 diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx index 66fbc6009100a..49db49f48d372 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx @@ -422,7 +422,7 @@ const randomUser = data.results[0]; :::note Astro v3.0 将包括一个新的 `astro:assets` 模块,并将弃用现有的 `@astrojs/image` 集成。 -访问 `astro:assets` 目前可以在实验标志下使用,并且是开始新 Astro 项目的推荐方式。如果你要迁移到 Astro pre-v3.0,我们建议你 [启用实验标志以使用 assets](/zh-cn/guides/assets/) 作为图像解决方案。 +访问 `astro:assets` 目前可以在实验标志下使用,并且是开始新 Astro 项目的推荐方式。如果你要迁移到 Astro pre-v3.0,我们建议你 [启用实验标志以使用 assets](/zh-cn/guides/images/) 作为图像解决方案。 ::: 用[ Astro 自己的图片集成组件](/zh-cn/guides/images/#astro-的图片集成),或用标准的HTML``来转换任何Next``组件。请看[组件属性的完整列表](/zh-cn/guides/integrations-guide/image/#使用),可用于Astro的``和``组件,注意有几个属性和Next不同。 diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx index fbe2c9afac83f..683315814b158 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx @@ -492,7 +492,7 @@ p { :::note Astro v3.0 将包括一个全新的 `astro:assets` 模块,并将废弃现有的 `@astrojs/image` 集成。 -目前通过实验性标志可以访问 `astro:assets` ,这也是开始新 Astro 项目的推荐方式。如果你需要迁移到 Astro v3.0之前的版本,我们建议 [启用实验性标志来使用资源](/zh-cn/guides/assets/) 作为图像的解决方案。 +目前通过实验性标志可以访问 `astro:assets` ,这也是开始新 Astro 项目的推荐方式。如果你需要迁移到 Astro v3.0之前的版本,我们建议 [启用实验性标志来使用资源](/zh-cn/guides/images/) 作为图像的解决方案。 ::: 将任何 [Nuxt `` 或 `` 组件](https://image.nuxtjs.org/components/nuxt-img) 转换为 [Astro 的图像集成组件](/zh-cn/guides/images/#astro-的图片集成),或者转换为标准的 HTML `` 标签。 diff --git a/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx b/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx index 6f0b3b25c1e71..42d28daf4fc45 100644 --- a/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx +++ b/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx @@ -21,4 +21,4 @@ const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); **另请参阅:** -- [资源(实验性)](/zh-cn/guides/assets/) +- [资源(实验性)](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/expected-image.mdx b/src/content/docs/zh-cn/reference/errors/expected-image.mdx index 563f13a8d9e30..a475f60cda0e5 100644 --- a/src/content/docs/zh-cn/reference/errors/expected-image.mdx +++ b/src/content/docs/zh-cn/reference/errors/expected-image.mdx @@ -24,4 +24,4 @@ import myImage from "../assets/my_image.png"; **另请参阅:** -- [资源(实验性)](/zh-cn/guides/assets/) +- [资源(实验性)](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx b/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx index b84e1c043a719..884b589aa2a68 100644 --- a/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx @@ -14,6 +14,5 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ **请参阅:** -- [资源(实验性)](/zh-cn/guides/assets/) -- [Image 组件](/zh-cn/guides/assets/#image--astroassets) -- [Image 组件的 alt 属性](/zh-cn/guides/assets/#alt-required) +- [资源(实验性)](/zh-cn/guides/images/) + diff --git a/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx b/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx index 73a4479821368..14e045a9ff891 100644 --- a/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx +++ b/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx @@ -25,4 +25,4 @@ import myImage from "../my_image.png"; **请参阅:** -- [资源(实验性)](/zh-cn/guides/assets/) +- [资源(实验性)](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx b/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx index 4f343278effcc..b73bd26763055 100644 --- a/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx +++ b/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx @@ -14,4 +14,4 @@ Markdown 中的图像是相对于当前文件的。要引用与 `.md` 文件位 **请参见:** -- [资源(实验性)](/zh-cn/guides/assets/) +- [资源(实验性)](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx b/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx index a6284dc6753dd..d237aeacc2ffb 100644 --- a/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx @@ -13,5 +13,5 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ **请参阅:** -- [资源(实验性)](/zh-cn/guides/assets/) -- [Image 组件的宽度和高度](/zh-cn/guides/assets/#width-and-height) +- [资源(实验性)](/zh-cn/guides/images/) + diff --git a/src/content/docs/zh-cn/reference/image-service-reference.mdx b/src/content/docs/zh-cn/reference/image-service-reference.mdx index 7ea1ffe5710b2..18cca5d056b7b 100644 --- a/src/content/docs/zh-cn/reference/image-service-reference.mdx +++ b/src/content/docs/zh-cn/reference/image-service-reference.mdx @@ -3,7 +3,7 @@ title: 图像服务 API i18nReady: true --- -Astro [assets](/zh-cn/guides/assets/) 旨在使任何图像优化服务都能轻松地在 Astro 上构建服务。 +Astro [assets](/zh-cn/guides/images/) 旨在使任何图像优化服务都能轻松地在 Astro 上构建服务。 :::caution 图像服务 API 是 Astro v2.1 中引入的一个实验性功能。该 API 在标记为稳定之前可能会发生更改。 From bc861539172bb7c752f688d668ba12a41fbceb02 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Wed, 16 Aug 2023 23:25:58 +0000 Subject: [PATCH 34/58] move non-en images pages to old translations; update migrate-to links --- {src/content/docs => old-translations}/de/guides/images.mdx | 0 {src/content/docs => old-translations}/es/guides/images.mdx | 0 {src/content/docs/fr/guides => old-translations/fr}/images.mdx | 0 {src/content/docs/ja/guides => old-translations/ja}/images.mdx | 0 {src/content/docs => old-translations}/pt-br/guides/images.mdx | 0 .../docs/zh-cn => old-translations/zh-CN}/guides/images.mdx | 2 +- .../docs/en/reference/errors/missing-image-dimension.mdx | 2 +- src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx | 2 +- src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx | 2 +- src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx | 2 +- src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx | 2 +- src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx | 2 +- src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx | 2 +- 13 files changed, 8 insertions(+), 8 deletions(-) rename {src/content/docs => old-translations}/de/guides/images.mdx (100%) rename {src/content/docs => old-translations}/es/guides/images.mdx (100%) rename {src/content/docs/fr/guides => old-translations/fr}/images.mdx (100%) rename {src/content/docs/ja/guides => old-translations/ja}/images.mdx (100%) rename {src/content/docs => old-translations}/pt-br/guides/images.mdx (100%) rename {src/content/docs/zh-cn => old-translations/zh-CN}/guides/images.mdx (97%) diff --git a/src/content/docs/de/guides/images.mdx b/old-translations/de/guides/images.mdx similarity index 100% rename from src/content/docs/de/guides/images.mdx rename to old-translations/de/guides/images.mdx diff --git a/src/content/docs/es/guides/images.mdx b/old-translations/es/guides/images.mdx similarity index 100% rename from src/content/docs/es/guides/images.mdx rename to old-translations/es/guides/images.mdx 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/src/content/docs/ja/guides/images.mdx b/old-translations/ja/images.mdx similarity index 100% rename from src/content/docs/ja/guides/images.mdx rename to old-translations/ja/images.mdx diff --git a/src/content/docs/pt-br/guides/images.mdx b/old-translations/pt-br/guides/images.mdx similarity index 100% rename from src/content/docs/pt-br/guides/images.mdx rename to old-translations/pt-br/guides/images.mdx diff --git a/src/content/docs/zh-cn/guides/images.mdx b/old-translations/zh-CN/guides/images.mdx similarity index 97% rename from src/content/docs/zh-cn/guides/images.mdx rename to old-translations/zh-CN/guides/images.mdx index b315d13e89864..a71300741771a 100644 --- a/src/content/docs/zh-cn/guides/images.mdx +++ b/old-translations/zh-CN/guides/images.mdx @@ -160,4 +160,4 @@ Image CDN 可与 Astro 配合使用,可将图片的完整网址作为 `` ## 社区开发的集成 -除了官方的 [`@astrojs/image`](/zh-cn/guides/integrations-guide/image/) 集成外,社区还开发了[社区图片集成](https://astro.build/integrations?search=images),用于处理和优化 Astro 项目中的图片。 +除了官方的 [`@astrojs/image`](/zh-cn/guides/integrations-guid/image/) 集成外,社区还开发了[社区图片集成](https://astro.build/integrations?search=images),用于处理和优化 Astro 项目中的图片。 diff --git a/src/content/docs/en/reference/errors/missing-image-dimension.mdx b/src/content/docs/en/reference/errors/missing-image-dimension.mdx index be637d2e64d36..1359f4161821e 100644 --- a/src/content/docs/en/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/en/reference/errors/missing-image-dimension.mdx @@ -22,6 +22,6 @@ If your image is inside your `src` folder, you probably meant to import it inste **See Also:** - [Assets (Experimental)](/en/guides/images/) -- [Image component#width-and-height](/en/guides/images/#width-and-height-required-for-public-and-remote-images) +- [Image component#width-and-height](/en/guides/images/#width-and-height) 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 9e4b37c77e956..4e61c904758df 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 @@ -339,7 +339,7 @@ import rocket from '../images/rocket.svg'; A rocketship in space. ``` -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. +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/image/) disponibles para estos componentes, y debes tener en cuenta que varios atributos difieren 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). 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 899b1ccbfd2ba..0629e22f1a697 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 @@ -426,7 +426,7 @@ Astro v3.0 incluirá un nuevo módulo `astro:assets` y descontinuará la integra 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/images/) como solución de imagen. ::: -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. +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/image/) disponibles para los componentes `` y `` de Astro, y ten en cuenta que varios difieren de los atributos de Next. ```astro title="src/pages/index.astro" --- 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 377a159fe2cd0..8b21b87d85b3e 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 @@ -521,7 +521,7 @@ Accede a `astro:assets` actualmente está disponible bajo una flag experimental, 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. -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. +Mira una [lista completa de atributos de componentes](/es/guides/image/) disponibles para los componentes `` y `` de Astro, y ten en cuenta que varios serán diferentes a los atributos de Nuxt. ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx index 84ef3ecdb2641..103c8604b1852 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx @@ -338,7 +338,7 @@ import rocket from '../images/rocket.svg'; A rocketship in space. ``` -Astro 的 `` 和 `` 组件是实验性的,并且目前只在 `.astro` 和 `.mdx` 文件中工作。查看这些组件可用的[完整组件属性列表](/zh-cn/guides/integrations-guide/image/#使用),并注意其中几个会与 Gatsby 的属性不同。 +Astro 的 `` 和 `` 组件是实验性的,并且目前只在 `.astro` 和 `.mdx` 文件中工作。查看这些组件可用的[完整组件属性列表](/zh-cn/guides/images/),并注意其中几个会与 Gatsby 的属性不同。 要继续在 Markdown(`.md`)文件中使用标准 Markdown 语法(`![]()`)使用本地图像,请将图像移动到你的 `public/` 文件夹中。你可能需要更新链接到相对 URL。你也可以在这些文件中使用标准的 `` 标签。注意这些 [在 `public/` 中的图像不会被 Astro 优化](/zh-cn/guides/images/#public)。 diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx index 49db49f48d372..53c6b15878069 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx @@ -425,7 +425,7 @@ Astro v3.0 将包括一个新的 `astro:assets` 模块,并将弃用现有的 ` 访问 `astro:assets` 目前可以在实验标志下使用,并且是开始新 Astro 项目的推荐方式。如果你要迁移到 Astro pre-v3.0,我们建议你 [启用实验标志以使用 assets](/zh-cn/guides/images/) 作为图像解决方案。 ::: -用[ Astro 自己的图片集成组件](/zh-cn/guides/images/#astro-的图片集成),或用标准的HTML``来转换任何Next``组件。请看[组件属性的完整列表](/zh-cn/guides/integrations-guide/image/#使用),可用于Astro的``和``组件,注意有几个属性和Next不同。 +用[ Astro 自己的图片集成组件](/zh-cn/guides/images/#astro-的图片集成),或用标准的HTML``来转换任何Next``组件。请看[组件属性的完整列表](/zh-cn/guides/images/),可用于Astro的``和``组件,注意有几个属性和Next不同。 ```astro title="src/pages/index.astro" --- diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx index 683315814b158..3243e32afa795 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx @@ -497,7 +497,7 @@ Astro v3.0 将包括一个全新的 `astro:assets` 模块,并将废弃现有 将任何 [Nuxt `` 或 `` 组件](https://image.nuxtjs.org/components/nuxt-img) 转换为 [Astro 的图像集成组件](/zh-cn/guides/images/#astro-的图片集成),或者转换为标准的 HTML `` 标签。 -请查看 Astro 的 `` 和 `` 组件的 [完整属性列表](/zh-cn/guides/integrations-guide/image/#使用),并且注意其中几个属性与 Nuxt 的属性有所不同。 +请查看 Astro 的 `` 和 `` 组件的 [完整属性列表](/zh-cn/guides/images/),并且注意其中几个属性与 Nuxt 的属性有所不同。 ```astro title="src/pages/index.astro" --- From a49f4c295cd9f72e771dd4279639277ffb50213c Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Thu, 17 Aug 2023 00:08:19 +0000 Subject: [PATCH 35/58] more link fixes in astro-components; missing-image-dimensions and from- guides --- src/content/docs/ar/core-concepts/astro-components.mdx | 2 +- .../docs/en/reference/errors/missing-image-dimension.mdx | 3 +-- src/content/docs/es/core-concepts/astro-components.mdx | 2 +- src/content/docs/es/guides/migrate-to-astro/from-gatsby.mdx | 6 +++--- src/content/docs/es/guides/migrate-to-astro/from-nextjs.mdx | 2 +- src/content/docs/es/guides/migrate-to-astro/from-nuxtjs.mdx | 4 ++-- src/content/docs/fr/core-concepts/astro-components.mdx | 2 +- src/content/docs/ja/core-concepts/astro-components.mdx | 2 +- src/content/docs/pt-br/core-concepts/astro-components.mdx | 2 +- src/content/docs/zh-cn/core-concepts/astro-components.mdx | 2 +- .../docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx | 4 ++-- .../docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx | 2 +- .../docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx | 2 +- 13 files changed, 17 insertions(+), 18 deletions(-) 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)، أو التعابير الديناميكية. - أي وسوم ` + +繁星点点的夜空。 + +``` + +#### 传递 Image 组件 + +`` 组件,就像任何其他 Astro 组件一样,**对 UI 框架组件不可用**。 + +但是,你可以将 `` 生成的静态内容作为子组件传递给 `.astro` 文件中的框架组件,或者使用 [命名的 ``](/zh-cn/core-concepts/framework-components/#我可以在我的框架组件中使用-astro-组件吗)。 + + +```astro title="ImageWrapper.astro" +--- +import ReactComponent from './ReactComponent.jsx'; +import { Image } from "astro:assets" +import stars from "~/stars/docline.png"; +--- + + + 繁星点点的夜空。 + +``` + +## 使用 `getImage()` 生成图像 + +:::caution +`getImage()` 依赖于仅在服务端可用的 API,当在客户端使用时会导致构建失败。 +::: + +`getImage()` 函数用于生成图像,这些图像将被用于除了直接在 HTML 中使用之外的其他地方,例如在 [API 路由](/zh-cn/core-concepts/endpoints/#服务器端点api-路由) 中。它还允许你创建自己的自定义 `` 组件。 + +`getImage()` 函数接受一个选项对象,其中包含与 [Image 组件](#属性) 相同的属性(除了 `alt`)。 + +```astro +--- +import { getImage } from "astro:assets"; +import myBackground from "../background.png" + +const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) +--- + +
+``` + +它返回一个具有以下属性的对象: + +```js +{ + options: {...} // 传递的原始参数, + src: "https//..." // 生成图像的路径, + attributes: {...} // 渲染图像所需的附加 HTML 属性(宽度、高度、样式等) +} +``` + +## 替代文本 + +不是所有用户都能以相同的方式看到图像,因此在使用图像时,无障碍性尤为重要。使用 `alt` 属性为图像提供 [描述性的 alt 文本](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(), + }, +}); +``` + +## 社区集成 + +这里有几个第三方 [社区图像集成](https://astro.build/integrations?search=images),用于优化和处理 Astro 项目中的图像。 + +## 从 v2.x 升级到 v3.0 + +`astro:assets` 不再是 Astro v3.0 中的实验性标志。 + +`` 现在是内置组件,之前的 `@astrojs/image` 集成已被删除。 + +当你从早期版本升级你的 Astro 项目时,这些和其他伴随的更改,可能会导致一些破坏性的变化。 + +请根据需要按照以下说明将 Astro v2.x 项目升级到 v3.0。 + +### 从 `experimental.assets` 升级 + +如果你之前启用了 `astro:assets` 的实验性标志,你需要更新你的项目到 Astro v3.0,它现在默认包含了 assets 功能。 + +#### 移除 `experimental.assets` 标志 + +移除实验性标志: + +```js title="astro.config.mjs" del={4-6} +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + experimental: { + assets: true + } +}); +``` + +如果需要,还可以更新你的 `src/env.d.ts` 文件,将 `astro/client-image` 引用替换为 `astro/client`: + +```ts title="src/env.d.ts" del={1} ins={2} +/// +/// +``` + +#### 移除`~/assets` 导入别名 + +这个导入别名不再默认包含在 `astro:assets` 中。如果你之前使用这个别名,你必须将它们转换为相对文件路径,或者 [创建你自己的导入别名](/zh-cn/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'; +--- +``` + +#### 为 Cloudflare, Deno, Vercel Edge 和 Netlify Edge 添加简单的资源支持 + + Astro v3.0 允许 `astro:assets` 在 Cloudflare、Deno、Vercel Edge 和 Netlify Edge 中无错误地工作,这些环境不支持 Astro 的内置 Squoosh 和 Sharp 图像优化。请注意,Astro 不会在这些环境中执行任何图像转换和处理。但是,你仍然可以享受使用 `astro:assets` 的其他好处,包括没有累积布局移位(CLS)、强制执行的 `alt` 属性和一致的创作体验。 + + 如果你之前因为这些限制而避免使用 `astro:assets`,现在你可以在没有问题的情况下使用它们。你可以配置无操作图像服务来显式地选择这种行为: + + ```astro + // astro.config.mjs + export default { + image: { + service: { + entrypoint: 'astro/assets/services/noop' + } + } + } + ``` + +### 决定在哪里存储你的图像 + +请参阅 [图像指南](/zh-cn/guides/images/#在哪里存储图像) 来帮助你决定在哪里存储你的图像。你可能希望利用 `astro:assets` 带来的灵活性,来存储你的图像的新选项。例如,现在可以使用标准的 Markdown `![alt](src)` 语法,在 Markdown、MDX 和 Markdoc 中引用项目 `src/` 中的相对图像。 + +### 更新现有的 `` 标签 + +以前,导入图像将返回一个简单的 `string`,其中包含图像的路径。现在,导入的图像资源与以下签名相匹配: + +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` + +你必须更新任何现有 `` 标签的 `src` 属性(包括任何 [UI 框架组件中的图像](#框架组件中的图像)),你也可以更新从导入的图像中获得的其他属性。 + +```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={4} ins={6} +--- +import rocket from '../images/rocket.svg'; +--- +太空中的火箭飞船。 + +太空中的火箭飞船。 +``` + +### 更新你的 Markdown, MDX, 和 Markdoc 文件 + +现在可以使用标准的 Markdown `![alt](src)` 语法,在 Markdown、MDX 和 Markdoc 中引用项目 `src/` 中的相对图像。 + +这允许你将图像从 `public/` 目录移动到你的项目 `src/`,它们现在将被处理和优化。你现有的 `public/` 中的图像和远程图像仍然有效,但不会被 Astro 的构建过程优化。 + +```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/" +# 我的 Markdown 页面 + + +![A starry night sky.](../../images/stars.png) + + +![A starry night sky.](./stars.png) +``` + +如果你需要对图像属性做更多的控制,我们建议使用 `.mdx` 文件格式,除了 Markdown 语法,你还可以使用 Astro 的 `` 组件或 JSX `` 标签。使用 [MDX 集成](/zh-cn/guides/integrations-guide/mdx/) 为 Astro 添加对 MDX 的支持。 + +### 移除 `@astrojs/image` + + +如果你在 Astro v2.x 中使用了图像集成,请完成以下步骤: + +1. 移除 `@astrojs/image` 集成。 + + 你必须通过卸载并从你的 `astro.config.mjs` 文件中删除它,来 [移除集成](/zh-cn/guides/integrations-guide/#移除集成)。 + + ```js del={3,7} + // astro.config.mjs + import { defineConfig } from 'astro/config'; + import image from '@astrojs/image'; + + export default defineConfig({ + integrations: [ + image(), + ] + }) + ``` + +2. 迁移任何现有的 `` 组件。 + + 将所有 `import` 语句从 `@astrojs/image/components` 更改为 `astro:assets`,以便使用新的内置 `` 组件。 + + 移除任何当前不[支持的图像属性](/zh-cn/guides/images/#属性)。 + + 例如,`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 = "The Astro Logo"; + --- + + {localAlt} + ``` + +3. 移除任何现有的 `` 组件 + + 目前,内置的 assets 功能不包括 `` 组件。 + + 相反,你可以使用 HTML 图像属性 `srcset` 和 `sizes` 或 `` 标签进行艺术指导或创建响应式图像。 + +4. 卸载 Sharp + + [Sharp](https://github.com/lovell/sharp) 现在是 `astro:assets` 的默认图像服务。你不再需要在你的项目中本地安装这个依赖。 + + 使用你的包管理器卸载 Sharp,或者从你的 `package.json` 文件中手动删除。 + + 如果你想使用 [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(), + }, + }); + ``` + +### 更新内容集合结构 + +你现在可以在 frontmatter 中声明一个与内容集合条目相关联的图像,例如博客文章的封面图像,使用相对于当前文件夹的路径: + +内容集合中新的 `image` 助手可让你使用 Zod 验证图像元数据。了解更多关于 [如何在内容集合中使用图像](/zh-cn/guides/images/#内容集合中的图像) 的内容。 diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx index 7244c0f3e7c09..c4dd8722d7241 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-gatsby.mdx @@ -87,8 +87,6 @@ Gatsby 和 Astro 共享一些相似性,这将帮助你迁移你的项目: - **@astrojs/react**:在你的新 Astro 站点中重用一些现有的 React UI 组件,或者继续使用 React 组件。 -- **@astrojs/image**:用 Astro 自己的图像优化组件替换 Gatsby 的 Image 插件。(实验性的:仅在 `.astro` 和 `.mdx` 文件中工作。) - - **@astrojs/mdx**:从你的 Gatsby 项目中带来现有的 MDX 文件,或者在你的新 Astro 站点中使用 MDX。 ### 将你的代码放在 `src` 中 @@ -320,41 +318,33 @@ Gatsby 中使用 `gatsby-browser.js` 中的 CSS 导入实现全局样式。在 A ### Gatsby 图像插件转换为 Astro -:::note -Astro v3.0 将包含一个新的 `astro:assets` 模块,并将弃用现有的 `@astrojs/image` 集成。 - -目前已经可以通过实验性标志访问 `astro:assets`,并且这是开始新 Astro 项目的推荐方式。如果你正在迁移到 Astro pre-v3.0,我们建议[启用实验标志来使用资产](/zh-cn/guides/images/)作为图像解决方案。 -::: - -将 Gatsby 的 `` 和 `` 组件与 [Astro 自己的图像集成组件](/zh-cn/guides/images/) 或适当的标准 HTML `` / JSX `` 标签相互转换。 +根据情况在你的 React 组件中将 Gatsby 的 `` 和 `` 组件转换为 [Astro 自己的图像集成组件](/zh-cn/guides/images/#image--astroassets) 或者转化成 [标准的 HTML `` / JSX `` 标签](/zh-cn/guides/images/#框架组件中的图像)。 ```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'; --- -The Astro Logo -A rocketship in space. +太空中的火箭飞船。 +太空中的火箭飞船。 ``` -Astro 的 `` 和 `` 组件是实验性的,并且目前只在 `.astro` 和 `.mdx` 文件中工作。查看这些组件可用的[完整组件属性列表](/zh-cn/guides/images/),并注意其中几个会与 Gatsby 的属性不同。 +Astro 的 `` 组件只能在 `.astro` 和 `.mdx` 文件中工作。查看该组件可用的[完整组件属性列表](/zh-cn/guides/images/#属性),并注意它与 Gatsby 的属性有一些不同。 -要继续在 Markdown(`.md`)文件中使用标准 Markdown 语法(`![]()`)使用本地图像,请将图像移动到你的 `public/` 文件夹中。你可能需要更新链接到相对 URL。你也可以在这些文件中使用标准的 `` 标签。注意这些 [在 `public/` 中的图像不会被 Astro 优化](/zh-cn/guides/images/)。 +要继续使用标准 Markdown 语法 (`![]()`) [在 Markdown (`.md`) 文件中使用图像](/zh-cn/guides/images/#markdown-文件中的图像),你可能需要更新链接。对于本地图像,不支持在 `.md` 文件中直接使用 HTML `` 标签,必须转换为 Markdown 语法。 ```md -# My Markdown Page +# 我的 Markdown 页面 - -![A starry night sky.](/assets/stars.png) -A starry night sky. + +![A starry night sky.](../assets/stars.png) ``` 在 React(`.jsx`)组件中,使用标准的 JSX 图像语法(``)。Astro 不会优化这些图像,但你可以安装和使用 NPM 包以获得更大的灵活性。 -你可以在 Images Guide 中了解更多关于 [在 Astro 中使用图像](/zh-cn/guides/images/) 的信息。 +你可以在图像指南中了解更多关于 [在 Astro 中使用图像](/zh-cn/guides/images/) 的信息。 ### Gatsby GraphQL 转换为 Astro diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx index c6a3f093e220a..ff5cccf2181ae 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nextjs.mdx @@ -83,8 +83,6 @@ Next.js 和 Astro 有一些相似之处,可以帮助你迁移你的项目: - **@astrojs/react**:在你的新 Astro 网站上重用一些现有的 React UI 组件,或者继续用 React 组件来编写。 -- **@astrojs/image**:用 Astro 自己的图片优化组件来替代 Next 的 Image。(实验:只适用于`.astro`和`.mdx`文件)。 - - **@astrojs/mdx**:将现有的 Next 项目中的 MDX 文件导入,或在新的 Astro 站点中使用 MDX。 ### 将源码放在`src`目录内 @@ -418,31 +416,24 @@ const randomUser = data.results[0]; 查看更多关于 [在 Astro 中设计样式](/zh-cn/guides/styling/) 的信息。 ### 转换 Next 的 图像插件到 Astro - -:::note -Astro v3.0 将包括一个新的 `astro:assets` 模块,并将弃用现有的 `@astrojs/image` 集成。 - -访问 `astro:assets` 目前可以在实验标志下使用,并且是开始新 Astro 项目的推荐方式。如果你要迁移到 Astro pre-v3.0,我们建议你 [启用实验标志以使用 assets](/zh-cn/guides/images/) 作为图像解决方案。 -::: - -用[ Astro 自己的图片集成组件](/zh-cn/guides/images/),或用标准的HTML``来转换任何Next``组件。请看[组件属性的完整列表](/zh-cn/guides/images/),可用于Astro的``和``组件,注意有几个属性和Next不同。 + +根据情况在你的 React 组件中将任何 Next 的 `` 组件转换为 [Astro 自己的图像集成组件](/zh-cn/guides/images/#image--astroassets) 或者转化成 [标准的 HTML `` / JSX `` 标签](/zh-cn/guides/images/#框架组件中的图像)。 + +Astro 的 `` 组件只能在 `.astro` 和 `.mdx` 文件中工作。查看该组件可用的[完整组件属性列表](/zh-cn/guides/images/#属性),并注意它与 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'; --- -The Astro Logo -A rocketship in space. +太空中的火箭飞船。 +太空中的火箭飞船。 ``` 在React(`.jsx`)组件中,使用标准的JSX的图片语法(``)。Astro不会优化这些图片,但你也可以安装和使用NPM包以提升灵活性。 你可以在图像指南中了解更多关于[在Astro中使用图像](/zh-cn/guides/images/)的信息。 - - ## 示例: 数据请求 下面是一个Next.js Pokédex数据获取转换为Astro的例子。 diff --git a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx index a451bc4868219..285e8cf355180 100644 --- a/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx +++ b/src/content/docs/zh-cn/guides/migrate-to-astro/from-nuxtjs.mdx @@ -85,8 +85,6 @@ Nuxt 和 Astro 有一些相似之处,这些相似性能够帮助你完成迁 - **@astrojs/vue**:你可以在新的 Astro 网站中重用一些现有的 Vue UI 组件,或者继续使用 Vue 组件编写。 -- **@astrojs/image**:用 Astro 自己的图像优化组件来替代 Nuxt 的图像插件。 - - **@astrojs/mdx**:从你的 Nuxt 项目将现有的 MDX 文件带入,或者在新的 Astro 网站中使用 MDX。 ### 将你的源码放入 `src` 中 @@ -489,29 +487,22 @@ p { ### Nuxt 图片插件迁移到 Astro -:::note -Astro v3.0 将包括一个全新的 `astro:assets` 模块,并将废弃现有的 `@astrojs/image` 集成。 - -目前通过实验性标志可以访问 `astro:assets` ,这也是开始新 Astro 项目的推荐方式。如果你需要迁移到 Astro v3.0之前的版本,我们建议 [启用实验性标志来使用资源](/zh-cn/guides/images/) 作为图像的解决方案。 -::: - -将任何 [Nuxt `` 或 `` 组件](https://image.nuxtjs.org/components/nuxt-img) 转换为 [Astro 的图像集成组件](/zh-cn/guides/images/),或者转换为标准的 HTML `` 标签。 +根据情况在你的 Vue 组件中将任何 [Nuxt 的`` 或者 `` 组件](https://image.nuxtjs.org/components/nuxt-img) 转换为 [Astro 自己的图像集成组件](/zh-cn/guides/images/#image--astroassets) 或者转化成 [标准的 HTML `` 标签](/zh-cn/guides/images/#框架组件中的图像) 或者 `` 标签。 -请查看 Astro 的 `` 和 `` 组件的 [完整属性列表](/zh-cn/guides/images/),并且注意其中几个属性与 Nuxt 的属性有所不同。 +Astro 的 `` 组件只能在 `.astro` 和 `.mdx` 文件中工作。查看该组件可用的[完整组件属性列表](/zh-cn/guides/images/#属性),并注意它与 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'; --- -The Astro Logo -A rocketship in space. +太空中的火箭飞船。 +太空中的火箭飞船。 ``` 在你的 Astro 应用中的 Vue (`.vue`) 组件中,使用标准的 JSX 图像语法 (``)。Astro 不会对这些图像进行优化,但你可以安装和使用 NPM 包以获得更大的灵活性。 -你可以在 [图像在 Astro 中的使用指南](/zh-cn/guides/images/) 中了解更多信息。 +你可以在图像指南中了解更多关于 [在 Astro 中使用图像](/zh-cn/guides/images/) 的信息。 ## 指导示例:请查看以下步骤: diff --git a/src/content/docs/zh-cn/reference/configuration-reference.mdx b/src/content/docs/zh-cn/reference/configuration-reference.mdx index c3cd186ac4b73..ac571e8c85a2e 100644 --- a/src/content/docs/zh-cn/reference/configuration-reference.mdx +++ b/src/content/docs/zh-cn/reference/configuration-reference.mdx @@ -646,6 +646,14 @@ export default defineConfig({ } ``` +### image.domains + +占位 + +### image.remotePatterns + +占位 + ### image.domains(实验性)

diff --git a/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx b/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx index 42d28daf4fc45..fb407790d48d4 100644 --- a/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx +++ b/src/content/docs/zh-cn/reference/errors/expected-image-options.mdx @@ -21,4 +21,4 @@ const optimizedImage = await getImage({src: myImage, width: 300, height: 300}); **另请参阅:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/expected-image.mdx b/src/content/docs/zh-cn/reference/errors/expected-image.mdx index a475f60cda0e5..1184a2295d4bb 100644 --- a/src/content/docs/zh-cn/reference/errors/expected-image.mdx +++ b/src/content/docs/zh-cn/reference/errors/expected-image.mdx @@ -24,4 +24,4 @@ import myImage from "../assets/my_image.png"; **另请参阅:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx b/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx index 884b589aa2a68..94a89c88d34c7 100644 --- a/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx +++ b/src/content/docs/zh-cn/reference/errors/image-missing-alt.mdx @@ -14,5 +14,7 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ **请参阅:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) +- [Image 组件](/zh-cn/guides/images/#image--astroassets) +- [Image 组件的 alt 属性](/zh-cn/guides/images/#alt-必须) diff --git a/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx b/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx index 14e045a9ff891..005f2efab9d74 100644 --- a/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx +++ b/src/content/docs/zh-cn/reference/errors/local-image-used-wrongly.mdx @@ -25,4 +25,4 @@ import myImage from "../my_image.png"; **请参阅:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx b/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx index b73bd26763055..1747bfda464e4 100644 --- a/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx +++ b/src/content/docs/zh-cn/reference/errors/markdown-image-not-found.mdx @@ -14,4 +14,4 @@ Markdown 中的图像是相对于当前文件的。要引用与 `.md` 文件位 **请参见:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) diff --git a/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx b/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx index d237aeacc2ffb..6970789b7eb0e 100644 --- a/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx +++ b/src/content/docs/zh-cn/reference/errors/missing-image-dimension.mdx @@ -13,5 +13,6 @@ githubURL: https://github.com/withastro/astro/blob/main/packages/astro/src/core/ **请参阅:** -- [资源(实验性)](/zh-cn/guides/images/) +- [图像](/zh-cn/guides/images/) +- [图像组件#宽高是必须的](/zh-cn/guides/images/#width-和-height-对于-public-和远程图像是必须的) diff --git a/src/content/docs/zh-cn/reference/image-service-reference.mdx b/src/content/docs/zh-cn/reference/image-service-reference.mdx index 72eb78a52eb96..88b7465f7d9a9 100644 --- a/src/content/docs/zh-cn/reference/image-service-reference.mdx +++ b/src/content/docs/zh-cn/reference/image-service-reference.mdx @@ -3,11 +3,7 @@ title: 图像服务 API i18nReady: true --- -Astro [assets](/zh-cn/guides/images/) 旨在使任何图像优化服务都能轻松地在 Astro 上构建服务。 - -:::caution -图像服务 API 是 Astro v2.1 中引入的一个实验性功能。该 API 在标记为稳定之前可能会发生更改。 -::: +`astro:assets` 旨在使任何图像优化服务都能轻松地在 Astro 上构建服务。 ## 什么是图像服务? @@ -228,9 +224,6 @@ export type ImageTransform = { import { defineConfig } from "astro/config"; export default defineConfig({ - experimental: { - assets: true, - }, image: { service: { entrypoint: "your-entrypoint", // 'astro/assets/services/squoosh' | 'astro/assets/services/sharp' | string, From fede45bc6f584a9b23aede5c28e07cf9a531bcfd Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Sun, 27 Aug 2023 07:27:25 -0300 Subject: [PATCH 50/58] Apply suggestions from morinokami code review Co-authored-by: Shinya Fujino --- src/content/docs/en/guides/images.mdx | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 8274d012caec8..fe18c03b06b82 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -37,10 +37,10 @@ Import and use Astro's built-in `` component for optimized images using ```astro title="src/pages/blog/MyImages.astro" --- import { Image } from 'astro:assets'; -import localBirdImage from ''../../images/subfolder/localBirdImage.png'; +import localBirdImage from '../../images/subfolder/localBirdImage.png'; --- A bird sitting on a nest of eggs. -A bird. +A bird. A bird. A bird sitting on a nest of eggs. @@ -86,7 +86,7 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 Currently, the built-in assets feature does not include a `` component. -Instead, you can [generate images or custom components using `getImage()`](/en/guides/images/#generating-images-with-getimage) that 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). +Instead, you can [generate images or custom components using `getImage()`](#generating-images-with-getimage) that 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). #### Properties @@ -101,7 +101,7 @@ The format of the `src` value of your image file depends on where your image fil import { Image } from 'astro:assets'; import myImportedImage from `../assets/my-local-image.png` --- - descriptive text + descriptive text ``` - **Images in the `public/` folder** - use the image's **file path relative to the public folder**: @@ -114,7 +114,8 @@ The format of the `src` value of your image file depends on where your image fil src="/images/my-public-image.png" alt="descriptive text" width="200" - height="150" /> + height="150" + /> ``` - **Remote images** - use the image's **full URL** as the property value: @@ -218,9 +219,9 @@ It accepts all HTML `` tag properties, and the only required property is `s Local images must be **imported from the relative path** from the existing `.astro` file, or configure and use an [import alias](/en/guides/aliases/). Then, you can access the image's `src` and other properties to use in the `` tag. -For example, use the image's own `height` and `width` properties by default to avoid CLS and improve Core Web Vitals. +For example, use the image's own `height` and `width` properties to avoid CLS and improve Core Web Vitals. -```astro "myDog.src" +```astro "myDog.width" "myDog.height" --- // import local images import myDog from `../../images/pets/local-dog.jpg` From fef8035895e994a070b09ff4a6d2267f5ef69dd3 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 29 Aug 2023 09:11:26 -0300 Subject: [PATCH 51/58] Everyone caught so many little fixes! MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elian ☕️ Co-authored-by: Shinya Fujino Co-authored-by: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> --- src/content/docs/en/guides/images.mdx | 45 ++++++++++++++------------- 1 file changed, 23 insertions(+), 22 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index fe18c03b06b82..7112206c67071 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -17,7 +17,7 @@ We recommend that local images are kept in `src/` when possible so that Astro ca Your local images stored in `src/` can be used by all files in your project: `.astro`, `.md`, `.mdx`, `.mdoc`, and other UI frameworks. Images can be stored in any folder, including alongside your content. -Store your images in the `public/` folder only if you want to avoid any processing. +Store your images in the `public/` folder if you want to avoid any processing or to have a direct public link to them. ### Remote images @@ -174,7 +174,7 @@ import myImage from "../assets/my_image.png"; ``` -```astro +```html @@ -425,7 +425,7 @@ Local images must **first be imported** to access their [image properties](#loca ```jsx title="src/components/ReactImage.jsx" import stars from "../assets/stars.png" -export default function ReactImgage () { +export default function ReactImage() { return ( A starry night sky. @@ -486,8 +486,8 @@ It returns an object with the following properties: ```js { - options: {...} // Original parameters passed, - src: "https//..." // Path to the generated image, + options: {...} // Original parameters passed + src: "https//..." // Path to the generated image attributes: {...} // Additional HTML attributes needed to render the image (width, height, style, etc..) } ``` @@ -543,7 +543,7 @@ import { defineConfig } from 'astro/config'; export default defineConfig({ experimental: { - assets: true + assets: true } }); ``` @@ -572,24 +572,25 @@ import rocket from '../../assets/rocket.png'; If you previously avoided using `astro:assets` because of these constraints, you can now use them without issues. You can configure the no-op image service to explicitly opt-in to this behavior: - ```astro - // astro.config.mjs - export default { - image: { - service: { - entrypoint: 'astro/assets/services/noop' - } - } - } - ``` +```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](/en/guides/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 `![alt](src)` syntax. +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 `![alt](src)` syntax. ### Update existing `` tags -Previously, importing an image would return a simple `string` with the path of the image. Now, imported image assets now match the following signature: +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 { @@ -615,7 +616,7 @@ import rocket from '../images/rocket.svg'; Relative images from your project `src/` can now be referenced in Markdown, MDX, and Markdoc using standard Markdown `![alt](src)` syntax. -This allows you the option 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. +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 @@ -674,13 +675,13 @@ If you were using the image integration in Astro v2.x, complete the following st /> ``` -3. Remove any existing `` components +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. Uninstall Sharp +4. Uninstall Sharp. [Sharp](https://github.com/lovell/sharp) is now the default image service used for `astro:assets`. You no longer need to install the dependency locally in your project. From 3ad56f15b3c42e419a39ae3e0e3f13a76a32b3ef Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 29 Aug 2023 09:14:53 -0300 Subject: [PATCH 52/58] extra line Co-authored-by: Shinya Fujino --- src/content/docs/en/guides/images.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 7112206c67071..a112acd403bf4 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -351,7 +351,6 @@ import rocket from '../assets/rocket.png'; A starry night sky. ![A starry night sky.](/images/stars.png) - // Remote image on another server From 5ea73c6724c8d34463907e4096f8f369d6eb4ec4 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 29 Aug 2023 09:15:10 -0300 Subject: [PATCH 53/58] another extra line Co-authored-by: Shinya Fujino --- src/content/docs/en/guides/images.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index a112acd403bf4..61994f15aa388 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -425,7 +425,6 @@ Local images must **first be imported** to access their [image properties](#loca import stars from "../assets/stars.png" export default function ReactImage() { - return ( A starry night sky. ) From a0bc8c528a725775caa452368185f12e3e90a825 Mon Sep 17 00:00:00 2001 From: Sarah Rainsberger Date: Tue, 29 Aug 2023 09:19:17 -0300 Subject: [PATCH 54/58] Rename and edit "4. Uninstall Sharp" --- src/content/docs/en/guides/images.mdx | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/content/docs/en/guides/images.mdx b/src/content/docs/en/guides/images.mdx index 61994f15aa388..2588b39f0a9d8 100644 --- a/src/content/docs/en/guides/images.mdx +++ b/src/content/docs/en/guides/images.mdx @@ -679,12 +679,9 @@ If you were using the image integration in Astro v2.x, complete the following st 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. Uninstall Sharp. - - [Sharp](https://github.com/lovell/sharp) is now the default image service used for `astro:assets`. You no longer need to install the dependency locally in your project. - - Uninstall Sharp using your package manager, or by removing manually from your `package.json`. +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: From 96eb5949d01623a51ffb9f68d2dbe0fbd21cee9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E7=91=9E=E4=B8=B0?= Date: Tue, 29 Aug 2023 23:59:01 +0800 Subject: [PATCH 55/58] i18n(zh-cn): Update zh from upstream (#4393) --- src/content/docs/zh-cn/guides/images.mdx | 64 ++++++++++++------------ 1 file changed, 31 insertions(+), 33 deletions(-) diff --git a/src/content/docs/zh-cn/guides/images.mdx b/src/content/docs/zh-cn/guides/images.mdx index ab0a301dd9627..5648616903755 100644 --- a/src/content/docs/zh-cn/guides/images.mdx +++ b/src/content/docs/zh-cn/guides/images.mdx @@ -16,7 +16,7 @@ Astro 为你提供了多种在网站上使用图像的方法,无论它们是 你在 `src/` 中存储的本地图像可以被项目中的所有文件使用:`.astro`、`.md`、`.mdx`、`.mdoc` 和其他 UI 框架。图像可以存储在任何文件夹中,包括与你的内容一起。 -只有当你想要避免任何处理时,才将图像存储在 `public/` 文件夹中。 +如果你想要避免对图像做任何处理或者想要直接公开链接到图像,请将图像存储在 `public/` 文件夹中。 ### 远程图像 @@ -35,10 +35,10 @@ Astro 可以使用 API 远程获取数据,也可以显示来自其完整 URL ```astro title="src/pages/blog/MyImages.astro" --- import { Image } from 'astro:assets'; -import localBirdImage from ''../../images/subfolder/localBirdImage.png'; +import localBirdImage from '../../images/subfolder/localBirdImage.png'; --- 一只鸟坐在蛋窝上。 -A bird. +A bird. A bird. 一只鸟坐在蛋窝上。 @@ -84,7 +84,7 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 目前,内置的 assets 功能不包括 `` 组件。 -相反,你可以 [使用 `getImage()` 生成图像或自定义组件](/zh-cn/guides/images/#使用-getimage-生成图像),这些组件使用 HTML 图像属性 `srcset` 和 `sizes` 或 `` 标签进行 [艺术指导或创建响应式图像](https://developer.mozilla.org/zh-CN/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction)。 +相反,你可以 [使用 `getImage()` 生成图像或自定义组件](#使用-getimage-生成图像),这些组件使用 HTML 图像属性 `srcset` 和 `sizes` 或 `` 标签进行 [艺术指导或创建响应式图像](https://developer.mozilla.org/zh-CN/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#art_direction)。 #### 属性 @@ -99,7 +99,7 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 import { Image } from 'astro:assets'; import myImportedImage from `../assets/my-local-image.png` --- - descriptive text + descriptive text ``` - **`public/` 文件夹中的图像** - 使用图像相对于 `public` 文件夹的**文件路径**作为属性值: @@ -112,7 +112,8 @@ import myImage from "../assets/my_image.png"; // Image is 1600x900 src="/images/my-public-image.png" alt="descriptive text" width="200" - height="150" /> + height="150" + /> ``` - **远程图像** - 使用图像的**完整 URL**作为属性值: @@ -170,7 +171,7 @@ import myImage from "../assets/my_image.png"; ``` -```astro +```html ` 标签中使用。 -例如,使用图像自己的 `height` 和 `width` 属性作为默认值,以避免布局位移累计 CLS 并改善核心 Web 性能指标。 +例如,使用图像自己的 `height` 和 `width` 属性,以避免布局位移累计 CLS 并改善核心 Web 性能指标。 -```astro "myDog.src" +```astro "myDog.width" "myDog.height" --- // 导入本地图像 import myDog from `../../images/pets/local-dog.jpg` @@ -297,7 +298,7 @@ export default defineConfig({ ## Markdown 文件中的图像 -在 `.md` 文件中使用标准的 Markdown `![alt](src)` 语法。这个语法可以与 Astro 的 Image Services API 一起使用,来优化你的本地图像和授权的远程图像。 +在 `.md` 文件中使用标准的 Markdown `![alt](src)` 语法。这个语法可以与 Astro 的 [图像服务 API](/zh-cn/reference/image-service-reference/) 一起使用,来优化你的本地图像和授权的远程图像。 ```md @@ -346,7 +347,6 @@ import rocket from '../assets/rocket.png'; A starry night sky. ![A starry night sky.](/images/stars.png) - // 其它服务上的远程图像 @@ -420,8 +420,7 @@ const allBlogPosts = await getCollection("blog"); ```jsx title="src/components/ReactImage.jsx" import stars from "../assets/stars.png" -export default function ReactImgage () { - +export default function ReactImage () { return ( 繁星点点的夜空。 ) @@ -481,8 +480,8 @@ const optimizedBackground = await getImage({src: myBackground, format: 'avif'}) ```js { - options: {...} // 传递的原始参数, - src: "https//..." // 生成图像的路径, + options: {...} // 传递的原始参数 + src: "https//..." // 生成图像的路径 attributes: {...} // 渲染图像所需的附加 HTML 属性(宽度、高度、样式等) } ``` @@ -539,7 +538,7 @@ import { defineConfig } from 'astro/config'; export default defineConfig({ experimental: { - assets: true + assets: true } }); ``` @@ -568,20 +567,21 @@ import rocket from '../../assets/rocket.png'; 如果你之前因为这些限制而避免使用 `astro:assets`,现在你可以在没有问题的情况下使用它们。你可以配置无操作图像服务来显式地选择这种行为: - ```astro - // astro.config.mjs - export default { - image: { - service: { - entrypoint: 'astro/assets/services/noop' - } - } - } - ``` + ```js title="astro.config.mjs" ins={4-8} + import { defineConfig } from 'astro/config'; + + export default defineConfig({ + image: { + service: { + entrypoint: 'astro/assets/services/noop' + } + } + }); + ``` ### 决定在哪里存储你的图像 -请参阅 [图像指南](/zh-cn/guides/images/#在哪里存储图像) 来帮助你决定在哪里存储你的图像。你可能希望利用 `astro:assets` 带来的灵活性,来存储你的图像的新选项。例如,现在可以使用标准的 Markdown `![alt](src)` 语法,在 Markdown、MDX 和 Markdoc 中引用项目 `src/` 中的相对图像。 +请参阅 [图像指南](#在哪里存储图像) 来帮助你决定在哪里存储你的图像。你可能希望利用 `astro:assets` 带来的灵活性,来存储你的图像的新选项。例如,现在可以使用标准的 Markdown `![alt](src)` 语法,在 Markdown、MDX 和 Markdoc 中引用项目 `src/` 中的相对图像。 ### 更新现有的 `` 标签 @@ -670,19 +670,17 @@ import rocket from '../images/rocket.svg'; /> ``` -3. 移除任何现有的 `` 组件 +3. 移除任何现有的 `` 组件。 目前,内置的 assets 功能不包括 `` 组件。 相反,你可以使用 HTML 图像属性 `srcset` 和 `sizes` 或 `` 标签进行艺术指导或创建响应式图像。 -4. 卸载 Sharp - - [Sharp](https://github.com/lovell/sharp) 现在是 `astro:assets` 的默认图像服务。你不再需要在你的项目中本地安装这个依赖。 +4. 选择一个默认图像服务。 - 使用你的包管理器卸载 Sharp,或者从你的 `package.json` 文件中手动删除。 + [Sharp](https://github.com/lovell/sharp) 现在是 `astro:assets` 的默认图像服务。如果你想使用 Sharp,无需任何配置。 - 如果你想使用 [Squoosh](https://github.com/GoogleChromeLabs/squoosh) 来转换你的图像,请使用以下配置更新你的配置: + 如果你想使用 [Squoosh](https://github.com/GoogleChromeLabs/squoosh) 来转换你的图像,请使用下面的 `image.service` 选项更新你的配置: ```js title="astro.config.mjs" ins={4-6} import { defineConfig, squooshImageService } from 'astro/config'; From c34e03075c7545277d470e971d34745b1e228239 Mon Sep 17 00:00:00 2001 From: Shinya Fujino Date: Wed, 30 Aug 2023 01:12:39 +0900 Subject: [PATCH 56/58] i18n(ja): Update images.mdx (#4418) Co-authored-by: Kyosuke Nakamura --- src/content/docs/ja/guides/images.mdx | 703 ++++++++++++++++++++++++++ 1 file changed, 703 insertions(+) create mode 100644 src/content/docs/ja/guides/images.mdx diff --git a/src/content/docs/ja/guides/images.mdx b/src/content/docs/ja/guides/images.mdx new file mode 100644 index 0000000000000..4155d08d93ead --- /dev/null +++ b/src/content/docs/ja/guides/images.mdx @@ -0,0 +1,703 @@ +--- +title: 画像 +description: Astroでの画像の使い方を学びます。 +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; + + +Astroでは、プロジェクト内にローカルに保存された画像、外部URLにリンクされた画像、CMSやCDNで管理されている画像などについて、これらをサイト上で使用するためのいくつかの方法を提供しています。 + +## 画像を保存する場所 + +### `src/`と`public/` + +ローカル画像は、Astroが変換、最適化、バンドルできるように、可能な限り`src/`に保存することをおすすめします。`/public`ディレクトリのファイルは、常にそのままビルドフォルダにコピーされ、処理されることはありません。 + +`src/`に保存されているローカル画像は、プロジェクト内のすべてのファイル(`.astro`、`.md`、`.mdx`、`.mdoc`、その他のUIフレームワーク)で使用できます。画像は、コンテンツと同じ場所など、任意のフォルダに保存できます。 + +画像に対する処理を避けたい場合や、画像へのリンクを直接公開したい場合は、画像を`public/`フォルダに保存します。 + +### リモート画像 + +コンテンツ管理システム(CMS)やデジタルアセット管理(DAM)プラットフォームなど、リモートに画像を保存することもできます。 + +外部ソースを扱う際の保護を強化するために、設定で指定した[許可された画像ソース](#リモート画像の許可)からのリモート画像のみ処理されます。ただし、リモート画像の表示は常に可能です。 + +Astroは、APIを使用してリモートからデータを取得したり、画像をそのフルURLパスから表示したりできます。一般的なサービスを組み込む例については、[CMSガイド](/ja/guides/cms/)を確認してください。 + +## `.astro`ファイル内の画像 + +`.astro`ファイルでローカル画像を使用するには、ファイルにインポートする必要があります。リモートと`public/`の画像はインポートする必要はありません。 + +`astro:assets`からAstro組み込みの``コンポーネントをインポートして使用すると、画像を最適化できます。また、Astro構文ではHTMLの``タグを直接書くこともできますが、画像処理はスキップされます。 + +```astro title="src/pages/blog/MyImages.astro" +--- +import { Image } from 'astro:assets'; +import localBirdImage from '../../images/subfolder/localBirdImage.png'; +--- +巣の中の卵を温めている鳥。 +鳥。 +鳥。 + +巣の中の卵を温めている鳥。 +鳥。 +鳥。 +``` + +### `` (`astro:assets`) + +Astro組み込みの``コンポーネントを使用して、ローカル画像と[設定済みのリモート画像](#リモート画像の許可)の最適化版を表示できます。 + +`public/`フォルダ内の画像とプロジェクトで明示的に設定されていないリモート画像もImageコンポーネントで使用できますが、最適化処理はおこなわれません。 + +``は、ローカルまたは許可されたリモート画像のサイズ、ファイルタイプ、品質を変換して、表示される画像を制御します。生成された``タグには、`alt`、`loading`、`decoding`属性が含まれており、また **Cumulative Layout Shift(CLS)** を回避するために画像のサイズを推測します。 + +:::tip[Cumulative Layout Shiftとは?] +[Cumulative Layout Shift(CLS)](https://web.dev/cls/)は、ローディング中にページのコンテンツがどれだけ移動したかを測定するためのCore Web Vitalのメトリックです。``コンポーネントは、ローカル画像の正しい`width`と`height`を自動的に設定することで、CLSへと最適化します。 +::: + +```astro title="src/components/MyComponent.astro" +--- +// Imageコンポーネントと画像をインポートする +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // 画像は1600x900 +--- + + +画像の説明。 +``` + +```html + + +画像の説明。 +``` + +現在、組み込みのassets機能には``コンポーネントは含まれていません。 + +代わりに、[アートディレクションやレスポンシブ画像を作成する](https://developer.mozilla.org/ja/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#アートディレクション)ために、HTMLの画像属性`srcset`と`sizes`または``タグを使用して、[`getImage()`により画像やカスタムコンポーネントを生成](#getimageで画像を生成する)できます。 + +#### プロパティ + +##### src (必須) + +画像ファイルの`src`値の形式は、画像ファイルの場所によって異なります。 + +- **`src/`内のローカル画像** - 相対ファイルパスを使用するか、または[インポートエイリアス](/ja/guides/aliases/)を設定して**、画像もインポート**する必要があります。インポート名を`src`値として使用します。 + + ```astro title="src/pages/index.astro" "myImportedImage" "{myImportedImage}" + --- + import { Image } from 'astro:assets'; + import myImportedImage from `../assets/my-local-image.png` + --- + 説明文 + ``` + +- **`public/`フォルダ内の画像** - 画像の**publicフォルダを起点としたファイルパス**を使用します。 + + ```astro title="src/pages/index.astro" '"/images/my-public-image.png"' + --- + import { Image } from 'astro:assets'; + --- + 説明文 + ``` + +- **リモート画像** - 画像の**フルURL**をプロパティ値として使用します。 + + ```astro title="src/pages/index.astro" '"https://example.com/remote-image.jpg"' + --- + import { Image } from 'astro:assets'; + --- + 説明文 + ``` + +##### alt (必須) + +必須の`alt`属性を使用して、画像の[説明的な代替テキスト](https://www.w3.org/WAI/tutorials/images/)の文字列を記述します。 + +画像が単に装飾用である場合(つまり、ページの理解に貢献していない場合)、スクリーンリーダーやその他の支援技術に画像を無視するよう伝えるために、`alt=""`を設定します。 + +##### widthとheight (`public/`とリモート画像の場合は必須) + +これらのプロパティは、画像に使用するサイズを定義します。 + +ローカル画像をオリジナルのアスペクト比で使用する場合、`width`と`height`はソースファイルから自動的に推測されるため、必須ではありません。 + +ただし、リモート画像と`public/`フォルダに保存されている画像については、Astroはこれらのファイルを解析できないため、両プロパティは必須となります。 + +##### format + +オプションで、使用する[画像ファイルタイプ](https://developer.mozilla.org/ja/docs/Web/Media/Formats/Image_types#一般的な画像ファイルの種類)の出力を指定できます。 + +デフォルトでは、``コンポーネントは`.webp`ファイルを出力します。 + +##### quality + +`quality`はオプションのプロパティで、次のいずれかの値を取ります。 +- フォーマット間で自動的に正規化されるプリセット(`low`、`mid`、`high`、`max`)。 +- (フォーマット間で異なる解釈となる)`0`から`100`までの数値。 + + +##### その他のプロパティ + +以上のプロパティに加えて、``コンポーネントは、HTMLの``タグに設定可能なすべてのプロパティを受け付けます。 + +たとえば、最終的な``要素に`class`を指定できます。 + +```astro title="src/pages/index.astro" +--- +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; +--- + + + +``` + +```html + + +``` + +#### デフォルト値の設定 + +現在、すべての``コンポーネントに対してデフォルト値を指定する方法はありません。必須属性は個々のコンポーネントに設定する必要があります。 + +再利用性を高めるための代替案として、``コンポーネントを別のAstroコンポーネントでラップできます。たとえば以下のようにして、ブログ記事の画像用コンポーネントを作成できます。 + +```astro title="src/components/BlogPostImage.astro" +--- +import { Image } from 'astro:assets'; + +const {src, ...attrs} = Astro.props; +--- + + + +``` + +### `` + +[Astroテンプレートの構文](/ja/core-concepts/astro-syntax/)では、最終的な出力を完全に制御可能な``タグを直接書くこともできます。これらの画像は処理されず、最適化もされません。 + +すべてのHTMLの``タグのプロパティを記述でき、必須のプロパティは`src`のみです。 + +#### `src/`内のローカル画像 + +ローカル画像は、`.astro`ファイルからの相対パスにより**インポート**するか、[インポートエイリアス](/ja/guides/aliases/)を設定して使用する必要があります。これにより、``タグで使用する画像の`src`やその他のプロパティにアクセスできます。 + +たとえば、CLSを回避しCore Web Vitalsを改善するために、画像の`height`と`width`プロパティを使用します。 + +```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/`にある画像の場合は、`src`の値に画像の**publicフォルダを起点としたファイルパス**を使用します。 + +```astro '"/images/public-cat.jpg"' +眠る猫。 +``` + +#### リモート画像 + +リモート画像の場合は、`src`の値に画像の**フルURL**を使用します。 + +```astro '"https://example.com/remote-cat.jpg"' +眠る猫。 +``` + +### ``と``の選択 + +``コンポーネントは、画像を最適化し、また(ローカル画像の場合は)オリジナルのアスペクト比に基づいて幅と高さを推測することでCLSを回避します。ただし、特定のフォーマットのみに対応しており、``要素はなく、`srcset`もサポートしていません。 + +以下のような``コンポーネントを使用できない場合に、HTMLの``要素を使用してください。 + - サポートされていない画像フォーマット + - Astroによる画像の最適化が不要な場合 + - クライアントサイドで`src`属性に動的にアクセスして変更する場合 + + +### リモート画像の許可 + +[`image.domains`](/ja/reference/configuration-reference/#imagedomains)と[`image.remotePatterns`](/ja/reference/configuration-reference/#imageremotepatterns)を使用して、画像の最適化に使用する、許可された画像ソースのURLドメインとパターンのリストを設定できます。この設定は、外部ソースから画像を表示する際にサイトを保護するために追加の安全性を提供します。 + +他のソースからのリモート画像は最適化されませんが、これらの画像に``コンポーネントを使用すると、Cumulative Layout Shift(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記法の`src`属性に、画像のフルURLを指定してください。リモート画像の最適化には、[許可されたドメインまたはURLパターンを設定](#リモート画像の許可)する必要があります。 + +あるいは、CDNがNode.js SDKを提供している場合は、プロジェクトでそれを使用することも可能です。たとえば[CloudinaryのSDK](https://cloudinary.com/documentation/node_integration)は、適切な`src`をもつ``タグを生成してくれます。 + +## Markdownファイル内の画像 + +`.md`ファイルでは、Markdown標準の`![alt](src)`構文を使用します。この構文は、Astroの[画像サービスAPI](/ja/reference/image-service-reference/)と連携して、ローカル画像と許可されたリモート画像を最適化します。 + +```md + + +# 私のMarkdownページ + + + +![満天の星空](../assets/stars.png) + + + +![満天の星空](/images/stars.png) + + + +![Astro](https://example.com/images/remote-image.png) +``` + +ローカル画像の場合``タグはサポートされておらず、また`.md`ファイルでは``コンポーネントは使用できません。 + +画像の属性をより細かく制御する必要がある場合は、Markdown構文に加えて、Astroの``コンポーネントや、JSXの``タグを使用可能な`.mdx`ファイル形式を使用することをおすすめします。AstroにMDXサポートを追加するには、[MDXインテグレーション](/ja/guides/integrations-guide/mdx/)を使用します。 + +## MDXファイル内の画像 + +コンポーネントと画像をインポートすることで、`.mdx`ファイル内でAstroの``コンポーネントとJSXの``タグを使用できます。使い方は[`.astro`ファイルの場合](#astroファイル内の画像)と同様です。 + +さらに、インポート不要で[Markdown標準の`![alt](src)`構文](#markdownファイル内の画像)もサポートされています。 + +```mdx title="src/pages/post-1.mdx" +--- +title: 私のページタイトル +--- +import { Image } from 'astro:assets'; +import rocket from '../assets/rocket.png'; + +# 私のMDXページ + +// src/assets/に置かれたローカル画像 +宇宙に浮かぶロケット。 +宇宙に浮かぶロケット。 +![宇宙に浮かぶロケット](../assets/rocket.png) + +// public/images/に置かれた画像 +満天の星空。 +満天の星空。 +![満天の星空](/images/stars.png) + +// 別のサーバー上のリモート画像 + + +![Astro](https://example.com/images/remote-image.png) + +``` + +## コンテンツコレクションと画像 + +ブログ記事のカバー画像など、コンテンツコレクションのエントリに関連付けられた画像を、現在のフォルダからの相対パスを使ってフロントマターに宣言できます。 + +```md title="src/content/blog/my-post.md" {3} +--- +title: "私の最初のブログ記事" +cover: "./firstpostcover.jpeg" # "src/content/blog/firstblogcover.jpeg"へと解決されます +coverAlt: "山々の向こうに沈む夕日の写真。" +--- + +これはブログ記事です +``` + +コンテンツコレクションスキーマの`image`ヘルパーにより、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: "カバー画像は幅1080ピクセル以上でなければなりません!", + }), + coverAlt: z.string(), + }), +}); + +export const collections = { + blog: blogCollection, +}; +``` + +画像はインポートされ、メタデータへと変換されます。これにより、``、``、そして`getImage()`に、`src`として渡すことができます。 + +以下の例は、上記のスキーマから各ブログ記事のカバー写真とタイトルをレンダリングする、ブログのインデックスページを示しています。 + +```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) => ( +

+ {post.data.coverAlt} +

+ {post.data.title} +

+
+ )) +} +``` + +## UIフレームワークコンポーネント内の画像 + +UIフレームワークコンポーネントに画像を追加する場合は、フレームワーク独自の画像構文を使用して画像をレンダリングします(たとえば、JSXの``、Svelteの``などです)。 + +ローカル画像は、`src`などの[画像プロパティ](src内のローカル画像)にアクセスするために**最初にインポート**する必要があります。 + +```jsx title="src/components/ReactImage.jsx" +import stars from "../assets/stars.png" + +export default function ReactImgage () { + return ( + 満天の星空。 + ) +} +``` + +```svelte title="src/components/SvelteImage.svelte" + + +満天の星空。 + +``` + +#### Imageコンポーネントを渡す + +``コンポーネントは、他のAstroコンポーネントと同様に、**UIフレームワークコンポーネントでは使用できません**。 + +しかし、`.astro`ファイル内のフレームワークコンポーネントに、``によって生成された静的コンテンツを子要素として渡すか、または[名前付きの``](/ja/core-concepts/framework-components/#フレームワークコンポーネントの中でastroコンポーネントを使用できますか)を使用して渡すことは可能です。 + + +```astro title="ImageWrapper.astro" +--- +import ReactComponent from './ReactComponent.jsx'; +import { Image } from "astro:assets" +import stars from "~/stars/docline.png"; +--- + + + 満天の星空。 + +``` + +## `getImage()`で画像を生成する + +:::caution +`getImage()`はサーバー専用のAPIに依存しており、クライアントで使用するとビルドが失敗します。 +::: + +`getImage()`関数は、たとえば[APIルート](/ja/core-concepts/endpoints/#サーバーエンドポイントapiルーティング)など、HTML以外の場所で使用する画像を生成することを目的としています。また、これを使って独自のカスタム``コンポーネントも作成できます。 + +`getImage()`は、(`alt`を除く)[Imageコンポーネントと同じプロパティ](#プロパティ)をもつオプションオブジェクトを受け取ります。 + +```astro +--- +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(), + }, +}); +``` + +## コミュニティインテグレーション + +Astroプロジェクトで画像を最適化したり、画像を扱ったりするための、サードパーティの[コミュニティインテグレーション](https://astro.build/integrations?search=images)があります。 + +## v2.xからv3.0へのアップグレード + +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} +/// +/// +``` + +#### `~/assets`インポートエイリアスの削除 + +このImportエイリアスは、`astro:assets`にデフォルトで含まれなくなりました。実験的なアセット機能でこのエイリアスを使用していた場合は、相対ファイルパスに変換するか、[自分でImportエイリアスを作成](/ja/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'; +--- +``` + +#### Cloudflare、Deno、Vercel Edge、Netlify Edge向けのシンプルなアセットサポートを追加する + +Astro v3.0では、Astro組み込みのSquooshとSharpによる画像最適化をサポートしていないCloudflare、Deno、Vercel Edge、Netlify Edgeでも、`astro:assets`をエラーなしで動作させることができます。Astroはこれらの環境では画像の変換や処理をおこないませんが、Cumulative Layout Shift(CLS)がなくなること、`alt`属性が必須であること、一貫したコードの書き心地など、`astro:assets`を使用した場合の他の利点は享受することができます。 + +こうした制約のために以前`astro:assets`の使用を避けていた場合でも、もう問題なく使用できるようになりました。この動作を明示的に有効にするために、no-op画像サービスを設定できます。 + +```js title="astro.config.mjs" ins={4-8} +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + image: { + service: { + entrypoint: 'astro/assets/services/noop' + } + } +}); +``` + +### 画像を保存する場所を決める + +[画像を保存する場所](#画像を保存する場所)を決めるには、今読んでいるこのガイドを参照してください。`astro:assets`がもたらす柔軟性を活用して、画像を保存するための新しいオプションを利用したい場合があるかもしれません。たとえば、プロジェクトの`src/`からの相対画像は、Markdown、MDX、MarkdocいずれにおいてもMarkdown標準の`![alt](src)`構文により参照できるようになりました。 + +### 既存の``タグを更新する + +以前は画像をインポートすると、画像のパスを含む単純な`string`が返されました。現在は、インポートされた画像アセットは以下のシグネチャをもつオブジェクトとなります。 + +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` + +([UIフレームワークコンポーネント内の画像](#uiフレームワークコンポーネント内の画像)を含む)既存の``タグの`src`属性の更新が必要です。また、インポートした画像から利用できるようになった他の属性も更新できます。 + +```astro title="src/components/MyComponent.astro" ".src" ".width" ".height" del={4} ins={6} +--- +import rocket from '../images/rocket.svg'; +--- +宇宙に浮かぶロケット。 + +宇宙に浮かぶロケット。 +``` + +### Markdown、MDX、Markdocファイルを更新する + +プロジェクトの`src/`からの相対画像は、Markdown、MDX、MarkdocいずれにおいてもMarkdown標準の`![alt](src)`構文により参照できるようになりました。 + +これにより、画像を`public/`ディレクトリからプロジェクトの`src/`に移動し、処理を加えて最適化できます。`public/`内の既存の画像とリモート画像は引き続き有効ですが、Astroのビルドプロセスでは最適化されません。 + +```md title="src/pages/posts/post-1.md" "/_astro" ".hash" "../../assets/" +# 私のMarkdownページ + + +![満天の星空。](../../images/stars.png) + + +![満天の星空。](./stars.png) +``` + +画像の属性をより細かく制御する必要がある場合は、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のロゴ"; + --- + + {localAlt} + ``` + +3. 既存の``コンポーネントを削除します。 + + 現在、組み込みのアセット機能には``コンポーネントは含まれていません。 + + 代わりに、HTMLの画像属性`srcset`と`sizes`、または``タグを使用して、[アートディレクションやレスポンシブ画像を作成](https://developer.mozilla.org/ja/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images#アートディレクション)できます。 + +4. デフォルトの画像サービスを選択します。 + + [Sharp](https://github.com/lovell/sharp)は、`astro:assets`で使用されるデフォルトの画像サービスとなりました。Sharpを使用する場合は、特に設定は必要ありません。 + + 画像を変換するために[Squoosh](https://github.com/GoogleChromeLabs/squoosh)を使用したい場合は、以下の`image.service`オプションを使用して設定を更新します。 + + ```js title="astro.config.mjs" ins={4-6} + import { defineConfig, squooshImageService } from 'astro/config'; + + export default defineConfig({ + image: { + service: squooshImageService(), + }, + }); + ``` + +### コンテンツコレクションのスキーマを更新する + +ブログ記事のカバー画像など、コンテンツコレクションのエントリに関連付けられた画像を、現在のフォルダからの相対パスによりフロントマターに宣言できるようになりました。 + +コンテンツコレクションの新しい`image`ヘルパーにより、Zodを使用して画像のメタデータを検証できるようになりました。コンテンツコレクションで画像を使用する方法について、詳しくは[こちら](#コンテンツコレクションと画像)を参照してください。 From af3a826d8e107be2b98560c7cc905d100efb5e8b Mon Sep 17 00:00:00 2001 From: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> Date: Tue, 29 Aug 2023 21:17:30 -0300 Subject: [PATCH 57/58] i18n(pt-BR): Update `images.mdx` for 3.0 (#4411) * i18n(pt-BR): Update `images.mdx` for 3.0 * Apply suggestions from translation review Co-authored-by: Alisson Nunes * oops, missed suggestion Co-authored-by: Alisson Nunes * Update translation based on latest changes * Fix typo * Fix links --------- Co-authored-by: Alisson Nunes --- old-translations/pt-br/guides/images.mdx | 162 ------ src/content/docs/pt-br/guides/images.mdx | 702 +++++++++++++++++++++++ 2 files changed, 702 insertions(+), 162 deletions(-) delete mode 100644 old-translations/pt-br/guides/images.mdx create mode 100644 src/content/docs/pt-br/guides/images.mdx diff --git a/old-translations/pt-br/guides/images.mdx b/old-translations/pt-br/guides/images.mdx deleted file mode 100644 index 0a62e008a01cb..0000000000000 --- a/old-translations/pt-br/guides/images.mdx +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Imagens -description: Aprenda como utilizar imagens no Astro. -i18nReady: true ---- -import Since from '~/components/Since.astro'; - - -Astro providencia diversas formas de você utilizar imagens em seu site, estejam elas armazenadas localmente dentro do seu projeto, vinculadas de uma fonte remota ou armazenadas em um CMS ou CDN! - -:::note[`astro:assets` (Experimental - chegando em v3.0)] -O módulo experimental `astro:assets` vai ser habilitado por padrão em `astro@3.0`. - -Siga o [Guia de Assets (Experimental)](/pt-br/guides/images/) para começar a usar a nova solução de imagens do Astro hoje mesmo! - -**Algumas das recomendações abaixo são incompatíveis com a flag experimental. Por favor veja a página de Assets se você estiver usando `astro:assets`.** -::: - -### Em arquivos `.astro` - -Astro utiliza elementos `` do HTML para mostrar imagens, sendo todos os atributos de imagens HTML suportados. - -O atributo `src` é obrigatório e seu formato irá depender de onde suas imagens são armazenadas, e caso você tenha habilitado o suporte experimental a assets: - -```astro title="src/pages/index.astro" ---- -import foguete from '../imagens/foguete.svg'; ---- - -Astro - - -O céu de uma noite estrelada. - - -Um foguete no espaço. -``` - -### Em arquivos Markdown - -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. - -Se você não consegue manter suas imagens em `public/`, nós recomendamos habilitar o [suporte experimental para assets](/pt-br/guides/images/), 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. - -```md - - -# Minha Página Markdown - - -![O céu de uma noite estrelada.](/assets/estrelas.png) -O céu de uma noite estrelada. - - -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro -``` - -### Em arquivos MDX - -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. - -Adicionalmente, você pode importar e utilizar imagens localizadas no diretório `src/` do seu projeto, assim como você faria em componentes Astro. - -```mdx title="src/pages/post-1.mdx" - -import foguete from '../imagens/foguete.svg'; - -# Minha Página MDX - -// Imagem local armazenada em src/imagens/foguete.svg -Um foguete no espaço. - -// Imagem local armazenada em public/assets/estrelas.png -![O céu de uma noite estrelada.](/assets/estrelas.png) -O céu de uma noite estrelada. - -// Imagem remota em outro servidor -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro -``` - -### Em Componentes de Frameworks de UI - -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 - -### `src/` - -Suas imagens armazenadas em `src/` podem ser utilizadas por componentes (`.astro`, `.mdx` e em outros frameworks de UI) mas não por arquivos Markdown. - -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 ---- -// src/pages/index.astro - -// Acesse imagens em `src/imagens/` -import logo from '../imagens/logo.png'; ---- -Astro -``` - -### `public/` - -Suas imagens armazenadas em `public/` podem ser utilizadas por componentes (`.astro`, `.mdx` e outros frameworks de UI) e também por arquivos Markdown. - - -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. - -O atributo `src` é **relativo ao diretório public**. No Markdown, você pode também utilizar a notação `![]()`. - -```astro title="src/pages/index.astro" ---- -// Acesse imagens in `public/imagens/` ---- - -``` - -### `src/assets/` (experimental) - -Veja o guia [Assets (Experimental)](/pt-br/guides/images/) para habilitar o uso experimental da pasta `/assets/`. - -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. - -## Integração Image do Astro - -:::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. - -Nós sugerimos remover ela assim que for conveniente e utilizar o módulo experimental `astro:assets` que fará parte do `astro@3.0`. - -Siga o [Guia de Assets (Experimental)](/pt-br/guides/images/) para começar a usar a nova solução de imagens do Astro hoje mesmo! - -**`astro:assets` não é um substituto completo do `@astrojs/image` nesse momento, mas está sob constante desenvolvimento.** -::: - -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) - -## Utilizando Imagens de um CMS ou CDN - -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. - -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ê. - -## 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. - -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. - -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. - - - -## Integrações da Comunidade - -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. diff --git a/src/content/docs/pt-br/guides/images.mdx b/src/content/docs/pt-br/guides/images.mdx new file mode 100644 index 0000000000000..70dce3d9d958e --- /dev/null +++ b/src/content/docs/pt-br/guides/images.mdx @@ -0,0 +1,702 @@ +--- +title: Imagens +description: Aprenda como utilizar imagens no Astro. +i18nReady: true +--- +import Since from '~/components/Since.astro'; +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; + +Astro fornece diversas formas de utilizar imagens no seu site, sejam elas armazenadas localmente dentro do seu projeto, vinculadas de uma URL externa, ou gerenciadas em um CMS ou CDN! + +## Onde armazenar imagens + +### `src/` vs `public/` + +Nós recomendamos que imagens locais sejam mantidas em `src/` quando possível para que o Astro possa transformar, otimizar e fazer bundle delas. Arquivos no diretório `/public` sempre são servidos ou copiados para a pasta da build como estão, com nenhum processamento. + +Suas imagens locais armazenadas em `src/` podem ser usadas por todos os arquivos em seu projeto: `.astro`, `.md`, `.mdx`, `.mdoc`, e outros frameworks de UI. Imagens podem ser armazenadas em qualquer pasta, incluindo ao lado do seu conteúdo. + +Armazene suas imagens na pasta `public/` se você quer evitar qualquer processamento ou para ter um link público direto para elas. + +### Imagens remotas + +Você pode também escolher armazenar suas imagens remotamente, em um sistema de gerenciamento de conteúdo (CMS, do inglês "content management system") ou plataforma de gerenciamento de assets digitais (DAM, do inglês "digital asset management"). + +Para proteção extra enquanto lida com fontes externas, imagens remotas serão apenas processadas de [fontes de imagem autorizadas](#autorizando-imagens-remotas) especificadas na sua configuração. Contudo, quaisquer imagens remotas podem ser mostradas. + +Astro pode buscar dados remotamente usando APIs ou mostrar imagens a partir de seus caminhos de URL completos. Veja nossos [guias de CMS](/pt-br/guides/cms/) para exemplos em como integrar serviços comuns. + + +## Imagens em arquivos `.astro` + +Em arquivos `.astro`, imagens locais devem ser importadas no arquivo para que sejam utilizadas. Imagens remotas e de `public/` não precisam ser importadas. + +Importe e utilize o componente `` integrado do Astro para imagens otimizadas utilizando `astro:assets`. Alternativamente, a sintaxe do Astro suporta escrever uma tag `` do HTML diretamente, o que pula o processamento de imagem. + +```astro title="src/pages/blog/MinhasImagens.astro" +--- +import { Image } from 'astro:assets'; +import imagemPassaroLocal from '../../imagens/subpasta/imagemPassaroLocal.png'; +--- +Um pássaro sentando em um ninho de ovos. +Um passáro. +Um passáro. + +Um pássaro sentando em um ninho de ovos. +Um passáro. +Um passáro. +``` + +### `` (`astro:assets`) + +Utilize o componente `` integrado do Astro para mostrar versões otimizadas de suas imagens locais e [imagens remotas configuradas](#autorizando-imagens-remotas). + +Imagens na pasta `public/`, assim como imagens remotas não especificadamente configuradas no seu projeto, também podem ser usadas com o componente Image, mas não serão processadas. + +`` pode transformar as dimensões, tipo de arquivo, e controle da qualidade da sua imagem mostrada local ou autorizada remota. A tag `` resultante inclui os atributos `alt`, `loading` e `decoding` e infere as dimensões da imagem para evitar **Cumulative Layout Shift (CLS)**. + +:::tip[O que é Cumulative Layout Shift?] +[Cumulative Layout Shift (CLS) ou Mudança Cumulativa de Layout](https://web.dev/cls/), é uma métrica do Core Web Vitals para mensurar o quanto o conteúdo da sua página se moveu durante o carregamento. O componente `` otimizada para CLS ao automaticamente definir o `width` e `height` corretos para suas imagens locais. +::: + +```astro title="src/components/MeuComponente.astro" +--- +// importe o componente Image e a imagem +import { Image } from 'astro:assets'; +import minhaImagem from "../assets/minha_imagem.png"; // Imagem é 1600x900 +--- + + +Uma descrição de minha imagem. +``` + +```html + + +Uma descrição de minha imagem. +``` + +Atualmente, a funcionalidade de assets integrado não inclui um componente ``. + +No lugar, você pode [gerar imagens ou componentes customizados utilizando `getImage()`](#gerando-imagens-com-getimage) que utiliza os atributos de imagem do HTML `srcset` e `sizes` ou a tag `` [para direção de arte ou para criar imagens responsivas](https://developer.mozilla.org/pt-BR/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images). + +#### Propriedades + +##### src (obrigatório) + +O formato do valor `src` de sua imagem depende de onde o seu arquivo de imagem está localizado: + +- **Imagens locais em `src/`** - você deve **também importar a imagem** utilizando um caminho de arquivo relativo ou configurar e utilizar um [atalho de importação](/pt-br/guides/aliases/). Então, utilize o nome de importação como o valor de `src`: + + ```astro title="src/pages/index.astro" "minhaImagemImportada" "{minhaImagemImportada}" + --- + import { Image } from 'astro:assets'; + import minhaImagemImportada from `../assets/minha-imagem-local.png` + --- + texto descritivo + ``` + +- **Imagens na pasta `public/`** - utilize o **caminho de arquivo da imagem relativo a pasta public**: + + ```astro title="src/pages/index.astro" '"/imagens/minha-imagem-publica.png"' + --- + import { Image } from 'astro:assets'; + --- + texto descritivo + ``` + +- **Imagens remotas** - utilize a **URL completa** da imagem como o valor da propriedade: + + ```astro title="src/pages/index.astro" '"https://exemplo.com/imagem-remota.jpg"' + --- + import { Image } from 'astro:assets'; + --- + texto descritivo + ``` + +##### alt (obrigatório) + +Utilize o atributo `alt` obrigatório para fornecer uma string de [texto alternativo descritivo](https://www.w3.org/WAI/tutorials/images/) para imagens. + +Se uma imagem é meramente decorativa (ou seja, não contribui para o entendimento da página), defina `alt=""` para que leitores de tela e outras tecnologias assistivas saibam ignorar a imagem. + +##### width e height (obrigatório para imagens remotas e de `public/`) + +Essas propriedades definem as dimensões a se utilizar para a imagem. + +Ao utilizar imagens em sua proporção de tela original, o `width` e `height` podem ser inferidos automaticamente do arquivo fonte e são opcionais. + +Porém, ambas essas propriedades são obrigatórias para imagens remotas e imagens armazenadas em sua pasta `public/` já que o Astro é incapaz de analisar esses arquivos. + +##### format + +Você pode opcionalmente definir um [tipo de arquivo de imagem](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) final para ser utilizado. + +Por padrão, o componente `` irá produzir um arquivo `.webp`. + +##### quality + +`quality` é uma propriedade que pode tanto ser: +- uma predefinição (`low`, `mid`, `high`, `max`) que é automaticamente normalizada entre formatos. +- um número de `0` a `100` (interpretado diferentemente entre formatos). + + +##### Propriedades adicionais + +Em adição as propriedades acima, o componente `` aceita todas as propriedades aceitas pela tag `` do HTML. + +Por exemplo, você pode fornecer uma `class` para o elemento `` final. + +```astro title="src/pages/index.astro" +--- +import { Image } from 'astro:assets'; +import minhaImagem from "../assets/minha_imagem.png"; +--- + + + +``` + +```html + + +``` + +#### Definindo Valores Padrões + +Atualmente, não há uma forma de especificar valores padrões para todos os componentes ``. Atributos obrigatórios devem ser definidos em cada componente individual. + +Como uma alternativa, você pode envolver esses componentes em outro componente Astro para reutilização. Por exemplo, você poderia criar um componente para suas imagens de postagens do blog: + +```astro title="src/components/ImagemPostBlog.astro" +--- +import { Image } from 'astro:assets'; + +const {src, ...attrs} = Astro.props; +--- + + + +``` + +### `` + +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 +Um cachorro latindo. +``` + +Assets de imagem importadas correspondem a seguinte assinatura: + +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` + +#### 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"' +Um gato dormindo. +``` + +#### Imagens remotas + +Para imagens remotas, utilize a **URL completa** da imagem como o valor de `src`: + +```astro '"https://exemplo.com/gato-remoto.jpg"' +Um gato dormindo. +``` + +### 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 `![alt](src)` 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 + + + +![Uma noite com um céu estrelado.](../assets/estrelas.png) + + + +![Uma noite com um céu estrelado.](/imagens/estrelas.png) + + + +![Astro](https://exemplo.com/imagens/imagem-remota.png) +``` + +A tag `` não é suportada para imagens locais, e o componente `` está indisponível em arquivos `.md`. + +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. + +## Imagens em arquivos 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). + +Adicionalmente, há suporte para [sintaxe padrão do Markdown `![alt](src)`](#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/assets/ +Um foguete no espaço. +Um foguete no espaço. +![Um foguete no espaço](../assets/foguete.png) + +// Imagens armazenada em public/imagens/ +Uma noite com um céu estrelado. +Uma noite com um céu estrelado. +![Uma noite com um céu estrelado.](/imagens/estrelas.png) + +// Imagem remota em outro servidor + + +![Astro](https://exemplo.com/imagens/imagem-remota.png) + +``` + +## 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) => ( +
+ {post.data.capaAlt} +

+ {post.data.titulo} +

+
+ )) +} +``` + +## 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 ( + Uma noite com um céu estrelado. + ) +} +``` + +```svelte title="src/components/ImagemSvelte.svelte" + + +Uma noite com um céu estrelado. + +``` + +#### Passando o componente Image + +O componente ``, assim como qualquer outro componente Astro, **não está disponível para componentes de frameworks de UI**. + +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): + + +```astro title="EnvolvedorImagem.astro" +--- +import ComponenteReact from './ComponenteReact.jsx'; +import { Image } from "astro:assets" +import estrelas from "~/estrelas/docline.png"; +--- + + + Uma noite com um céu estrelado. + +``` + +## 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 +--- +import { getImage } from "astro:assets"; +import meuPlanoFundo from "../planoFundo.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..) +} +``` + +## Texto Alternativo + +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. + +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. + +## Serviço de imagem padrão + +[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} +--- +import foguete from '~/assets/foguete.png' +import foguete from '../../assets/foguete.png'; +--- +``` + +#### Adicione suporte simples de assets para Cloudflare, Deno, Vercel Edge e Netlify Edge + +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. + +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: + +```js title="astro.config.mjs" ins={4-8} +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + image: { + service: { + entrypoint: 'astro/assets/services/noop' + } + } +}); +``` + +### Decida onde armazenar suas imagens + +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 `![alt](src)`. + +### Atualize tags `` existentes + +Anteriormente, importar uma imagem iria retornar uma simples `string` com o caminho da imagem. Agora, assets de imagem importadas correspodem a seguinte assinatura: + +```ts +interface ImageMetadata { + src: string; + width: number; + height: number; + format: string; +} +``` + +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. + +```astro title="src/components/MeuComponente.astro" ".src" ".width" ".height" del={4} ins={6} +--- +import foguete from '../imagens/foguete.svg'; +--- +Um foguete no espaço. + +Um foguete no espaço. +``` + +### Atualize seus arquivos Markdown, MDX e Markdoc + +Imagens relativas da `src/` do seu projeto agora podem ser referenciadas em Markdown, MDX e Markdoc utilizando a sintaxe padrão do Markdown `![alt](src)`. + +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 + + +![Uma noite com um céu estrelado.](../../imagens/estrelas.png) + + +![Uma noite com um céu estrelado.](./estrelas.png) +``` + +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"; + --- + + {altLocal} + ``` + +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. + +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 From bdbb59153772a7c8dcab8ad9e48d452ce2034b59 Mon Sep 17 00:00:00 2001 From: Yan Thomas <61414485+Yan-Thomas@users.noreply.github.com> Date: Wed, 30 Aug 2023 07:51:37 -0300 Subject: [PATCH 58/58] Bring back ES guide changes --- src/content/docs/es/guides/images.mdx | 688 +++++++++++++++++++++++--- 1 file changed, 616 insertions(+), 72 deletions(-) diff --git a/src/content/docs/es/guides/images.mdx b/src/content/docs/es/guides/images.mdx index f366d3d1ba39d..9387c318cdf10 100644 --- a/src/content/docs/es/guides/images.mdx +++ b/src/content/docs/es/guides/images.mdx @@ -4,152 +4,696 @@ description: Aprende cómo usar imágenes en Astro. i18nReady: true --- import Since from '~/components/Since.astro'; +import PackageManagerTabs from '~/components/tabs/PackageManagerTabs.astro'; +¡Astro ofrece varias formas para que uses imágenes en tu sitio, ya sea que estén almacenadas localmente dentro de tu proyecto, enlazadas desde una URL externa o gestionadas en un CMS o CDN! +## Dónde guardar las imágenes -¡Astro proporciona varias formas de usar imágenes en tu proyecto, tanto si están almacenadas localmente, enlazadas remotamente o almacenadas en un CMS o una CDN! +### `src/` vs. `public/` -:::note[`astro:assets` (Experimental - en camino para la versión v3.0)] -El modulo experimental `astro:assets` estará habilitado por defecto en `astro@3.0`. +Recomendamos que las imágenes locales se mantengan en `src/` cuando sea posible, para que Astro pueda transformar, optimizar y empaquetarlas. Los archivos en el directorio `/public` siempre se sirven o copian tal como están en la carpeta de construcción, sin ningún procesamiento. -¡Sigue la [Guía de Assets (Experimental)](/es/guides/images/) para comenzar a usar la nueva solución de imágenes de Astro hoy mismo! +Tus imágenes locales almacenadas en `src/` pueden ser utilizadas por todos los archivos en tu proyecto: `.astro`, `.md`, `.mdx`, `.mdoc` y otros frameworks UI. Las imágenes pueden almacenarse en cualquier carpeta, incluida junto a tu contenido. -**Algunos de los consejos a continuación son incompatibles con la bandera experimental. Consulta la página de Assets si estás usando `astro:assets`.** +Almacena tus imágenes en la carpeta `public/` si deseas evitar cualquier tipo de procesamiento o para tener un enlace público directo a ellas. + +### Imágenes remotas + +También puedes optar por almacenar tus imágenes de forma remota, en un sistema de gestión de contenido (CMS) o en una plataforma de gestión de assets digitales (DAM). + +Para una protección adicional al tratar con fuentes externas, las imágenes remotas solo se procesarán desde [fuentes de imágenes autorizadas](#autorizando-imágenes-remotas) especificadas en tu configuración. Sin embargo, cualquier imagen remota puede ser mostrada. + +Astro puede obtener tus datos de forma remota utilizando APIs o mostrar imágenes desde su ruta completa de URL. Consulta nuestras [guías de CMS](/es/guides/cms/) para ejemplos de integración con servicios comunes. + + +## Imágenes en archivos `.astro` + +En archivos `.astro`, las imágenes locales deben ser importadas al archivo para poder ser utilizadas. Las imágenes remotas y las imágenes en `public/` no requieren ser importadas. + +Importa y utiliza el componente incorporado `` de Astro para imágenes optimizadas usando `astro:assets`. Alternativamente, la sintaxis de Astro admite escribir directamente una etiqueta HTML ``, lo que omite el procesamiento de imágenes. + +```astro title="src/pages/blog/MyImages.astro" +--- +import { Image } from 'astro:assets'; +import localBirdImage from '../../images/subfolder/localBirdImage.png'; +--- +Un pájaro sentado sobre un nido de huevos. +Un pájaro. +Un pájaro. + +Un pájaro sentado sobre un nido de huevos. +Un pájaro. +Un pájaro. +``` + +### `` (`astro:assets`) + +Utiliza el componente integrado `` de Astro para mostrar versiones optimizadas de tus imágenes locales y [imágenes remotas configuradas](#autorizando-imágenes-remotas). + +Las imágenes en la carpeta `public/`, así como las imágenes remotas no configuradas específicamente en tu proyecto, también se pueden usar con el componente Image, pero no se procesarán. + +`` puede transformar las dimensiones, el tipo de archivo y la calidad de una imagen local o remota autorizada para un control sobre la imagen que se muestra. La etiqueta resultante `` incluye atributos `alt`, `loading` y `decoding`, e infiere las dimensiones de la imagen para evitar el **Desplazamiento Acumulativo de Diseño (CLS)**. + +:::tip[¿Qué es el Desplazamiento Acumulativo de Diseño?] +[Desplazamiento Acumulativo de Diseño (CLS)](https://web.dev/cls/) es una métrica de Core Web Vital para medir cuánto se ha desplazado el contenido de tu página durante la carga. El componente `` optimiza para el CLS al establecer automáticamente el `ancho` y el `alto` correctos para tus imágenes locales. ::: -### En archivos `.astro` +```astro title="src/components/MyComponent.astro" +--- +// Importa el componente Image y la imagen +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; // La imagen es 1600x900 +--- + + +Una descripción de mi imagen. +``` + +```html + + +Una descripción de mi imagen. +``` + +Actualmente, la característica integrada de assets no incluye un componente ``. + +En su lugar, puedes [generar imágenes o componentes personalizados usando `getImage()`](#generando-imágenes-con-getImage) que utilicen los atributos HTML de imagen `srcset` y `sizes` o la etiqueta `` [para la 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). -Astro utiliza elementos HTML `` para mostrar imágenes, y todos los atributos de imagen HTML son compatibles. +#### Propiedades -Se requiere el atributo `src` y su formato dependerá de dónde se almacenen las imágenes: +##### src (requerido) + +El formato del valor `src` de tu archivo de imagen depende de dónde esté ubicado tu archivo de imagen: + +- **Imágenes locales en `src/`** - también debes **importar la imagen** utilizando una ruta de archivo relativa o configurar y usar un [alias de importación](/es/guides/aliases/). Luego usa el nombre de importación como valor de `src`: + + ```astro title="src/pages/index.astro" "myImportedImage" "{myImportedImage}" + --- + import { Image } from 'astro:assets'; + import myImportedImage from `../assets/my-local-image.png` + --- + texto descriptivo + ``` + +- **Imágenes en la carpeta `public/`** - utiliza la **ruta de archivo de la imagen relativa a la carpeta public**: + + ```astro title="src/pages/index.astro" '"/images/my-public-image.png"' + --- + import { Image } from 'astro:assets'; + --- + texto descriptivo + ``` + +- **Imágenes remotas** - utiliza la **URL completa** de la imagen como valor de la propiedad: + + ```astro title="src/pages/index.astro" '"https://example.com/remote-image.jpg"' + --- + import { Image } from 'astro:assets'; + --- + texto descriptivo + ``` + +##### alt (requerido) + +Utiliza el atributo `alt` requerido para proporcionar un [texto alternativo descriptivo](https://www.w3.org/WAI/tutorials/images/) para las imágenes. + +Si una imagen es meramente decorativa (es decir, no contribuye a la comprensión de la página), establece `alt=""` para que los lectores de pantalla y otras tecnologías de asistencia sepan que deben ignorar la imagen. + +##### width y height (requerido para imágenes `public/` y remotas) + +Estas propiedades definen las dimensiones a utilizar para la imagen. + +Cuando se utilizan imágenes locales en su relación de aspecto original, el `width` y `height` pueden inferirse automáticamente a partir del archivo fuente y son opcionales. + +Sin embargo, ambas de estas propiedades son necesarias para imágenes remotas e imágenes almacenadas en tu carpeta `public/`, ya que Astro no puede analizar estos archivos. + +##### format + +Puedes opcionalmente indicar el [tipo de archivo de imagen](https://developer.mozilla.org/en-US/docs/Web/Media/Formats/Image_types#common_image_file_types) de salida que se va a utilizar. + +Por defecto, el componente `` producirá un archivo `.webp`. + +##### quality + +`quality` es una propiedad opcional que puede ser: +- un preajuste (`low`, `mid`, `high`, `max`) que se normaliza automáticamente entre los formatos. +- un número del `0` al `100` (interpretado de manera diferente entre los formatos). + +##### Propiedades adicionales + +Además de las propiedades mencionadas anteriormente, el componente `` acepta todas las propiedades aceptadas por la etiqueta HTML ``. + +Por ejemplo, puedes proporcionar una propiedad `class` al elemento `` final. ```astro title="src/pages/index.astro" --- -import rocket from '../images/rocket.svg'; +import { Image } from 'astro:assets'; +import myImage from "../assets/my_image.png"; --- - -Astro - -Un cielo nocturno estrellado. + + +``` - -Un cohete en el espacio. +```html + + ``` -### En archivos Markdown +#### Estableciendo valores por defecto -Puedes usar la sintaxis estándar de Markdown `![]()` o las etiquetas estándar de HTML `` en tus archivos `.md` para mostrar imágenes locales en tu carpeta `public/` o imágenes remotas en otro servidor. +Actualmente, no hay forma de especificar valores predeterminados para todos los componentes ``. Los atributos requeridos deben establecerse en cada componente individual. -Si no puedes almacenar tus imágenes en `public/`, te recomendamos usar el formato de archivo `.mdx` , que te permite combinar componentes importados con sintaxis de Markdown. Usa la [integración de MDX](/es/guides/integrations-guide/mdx/) para agregar soporte para MDX en Astro. +Como alternativa, puedes envolver estos componentes en otro componente de Astro para reutilizarlos. Por ejemplo, podrías crear un componente para las imágenes de tus entradas de blog: + +```astro title="src/components/BlogPostImage.astro" +--- +import { Image } from 'astro:assets'; + +const {src, ...attrs} = Astro.props; +--- + + + +``` + +### `` + +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 +Un perro ladrando. +``` + +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"' +Un gato dormiendo. +``` + +#### 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"' +Un gato dormiendo. +``` + +### 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 `![alt](src)` 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 - -![Un cielo nocturno estrellado.](/assets/stars.png) -Un cielo nocturno estrellado. + + +![Un cielo estrellado.](../assets/stars.png) + + + +![Un cielo estrellado.](/images/stars.png) -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro + +![Astro](https://example.com/images/remote-image.png) ``` -### 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 `![alt](src)`](#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 -Un cohete en el espacio. +// Imagen local almacenada en src/assets/ +Un cohete en el espacio. +Un cohete en el espacio. +![A rocketship in space](../assets/rocket.png) -// Imagen local almacenada en public/assets/stars.png -![Un cielo nocturno estrellado.](/assets/stars.png) -Un cielo nocturno estrellado. +// Imagen almacenada en public/images/ +Un cielo estrellado. +Un cielo estrellado. +![Un cielo estrellado.](/images/stars.png) // Imagen remota en otro servidor -![Astro](https://docs.astro.build/assets/logomark-light.png) -Astro + + +![Astro](https://example.com/images/remote-image.png) + ``` -### 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) => ( +
+ {post.data.coverAlt} +

+ {post.data.title} +

+
+ )) +} +``` + +## 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 ( + Un cielo estrellado. + ) +} +``` + +```svelte title="src/components/SvelteImage.svelte" + + +Un cielo estrellado. + +``` -### `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"; +--- + + + Un cielo estrellado. + +``` + +## 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'}) --- -Astro + +
``` -### `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 `![alt](src)`. + +### 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'; +--- +Un cohete en el espacio. + +Un cohete en el espacio. ``` -## 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 `![alt](src)`. -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/images/) 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.** -::: + +![Un cielo estrellado](../../images/stars.png) + + +![Un cielo estrellado](./stars.png) +``` + +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"; + --- + + {localAlt} + ``` + +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