Astro 3.0 was just released and it comes with a great image compression feature. The savings can be up to 99.1% less data based on testing I did with compressing .jpg
images directly from a camera. However, all the examples only show how to compress and import one image at a time. In this blog post, I'll show you how to use Astro's built-in Image
component to optimize all images in a folder with just a few lines of code. If you haven't done so already, create an Astro project and start a new component.
First, you need to import the Image
component from astro:assets
. This component will automatically compress and lazy load your images for the best quality and speed.
Next, you need to use Astro.glob
to import all your image files at once. This is a handy method that returns an array of files matching a glob pattern. You can use any valid glob pattern to filter the files by extension, name, or subfolder. For example, "../assets/images/*.{jpg,JPG,jpeg,png,PNG,webp}"
will get all the .jpg
, .png
and .webp
files from the ../assets/images/
folder.
Finally, the images.map
function loops over the array of files and renders each one to its own Image
component.
---
import { Image } from "astro:assets";
const images = await Astro.glob(
"../assets/images/*.{jpg,JPG,jpeg,png,PNG,webp}"
).then((files) => {
return files.map((file) => file.default); // Map each file to its default export (the src).
});
---
{
images.map((img) => (
<Image
src={img}
width="1200"
height="750"
/>
))
}
That's it! Now you have optimized all your images with Astro 3.0 and improved your website performance.
Top comments (0)