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
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 .jpg
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.Image
First, you need to import the
component from Image
. This component will automatically compress and lazy load your images for the best quality and speed.astro:assets
Next, you need to use
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, Astro.glob
"
will get all the ../assets/images/*.{jpg,JPG,jpeg,png,PNG,webp}
"
, .jpg
and .png
files from the .webp
folder.../assets/images/
Finally, the
function loops over the array of files and renders each one to its own images.map
component.Image
---
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.