Usage
Here is a brief overview on the usage of the Vite plugin, components and APIs provided by Astro ImageTools.
Plugin Usage
Astro ImageTools comes with a Vite plugin and it gets registered automatically once you add the integration. The Vite plugin is used by the components and APIs interally to perform all kinds of image transformations and optimizations. After itβs been registered, it starts looking for and handling image imports.
So, you can leverage the power of the plugin using ESM imports to perform simple image transformations and optimizations on your own. It may come in handy in the scenarios where using the provided components and APIs is not possible. Imports inside framework components too will be handled!
import React from "react";
// The Vite plugin will handle the below import automatically and return a path to the optimized image
import src from "../images/image.jpg";
export default function ReactImage() {
return <img src={src} />;
}
You can pass configuration options via query parameters.
import src from "../images/image.jpg?w=200&h=200&format=avif&q=80";
If you want the import to return a srcset
instead of a src
, pass multiple values to the w
or width
query parameter.
import srcset from "../images/image.jpg?w=200;400;800";
Components Usage
Astro ImageTools provides a set of components that abstract away all the complexities of image transformations and optimizations. The components are highly customizable and provide a number of excellent features.
All the components, Img
, Picture
, BackgroundImage
, BackgroundPicture
, and ImageSupportDetection
are exported using named exports from astro-imagetools/components
.
---
import { Picture } from "astro-imagetools/components";
---
You can pass configuration options to the components via props.
---
import { Picture } from "astro-imagetools/components";
---
<html>
<body>
<Picture
src="/src/images/landscape.jpg"
alt="A landscape image"
artDirectives={[
{
src: "/src/images/portrait.jpg",
media: "(orientation: potrait)",
},
]}
/>
</body>
</html>
To know more about the components and available configuration options, please check out the Components documentation.
APIs Usage
Astro ImageTools provides a set of APIs that allow you to generate the rendered HTML for the images programmatically.
All the APIs, renderImg
, renderPicture
, renderBackgroundImage
, and renderBackgroundPicture
are exported using named exports from astro-imagetools/api
.
---
import { renderPicture } from "astro-imagetools/api";
---
All the APIs support a single config object as the only argument. You can pass configuration options to the APIs via defining properties in the config object.
---
import { renderPicture } from "astro-imagetools/api";
const { link, style, picture } = await renderPicture({
src: "https://picsum.photos/1024/768",
alt: "A random image",
});
---
To know more about the APIs and available configuration options, please check out the APIs documentation.