0
0
Astroframework~30 mins

Image optimization with astro:assets - Mini Project: Build & Apply

Choose your learning style9 modes available
Image optimization with astro:assets
📖 Scenario: You are building a simple Astro website that shows a product image. To make the website faster and use less data, you want to optimize the image using Astro's built-in astro:assets feature.
🎯 Goal: Create an Astro component that imports an image file and uses astro:assets to optimize it. Then display the optimized image with a fixed width.
📋 What You'll Learn
Import an image file using astro:assets
Create a variable called optimizedImage to hold the optimized image
Set the image width to 300 pixels during optimization
Render the optimized image in an <img> tag with alt text
💡 Why This Matters
🌍 Real World
Optimizing images helps websites load faster and use less data, improving user experience especially on mobile devices.
💼 Career
Web developers often optimize images to improve site performance and SEO, making this skill valuable in frontend development roles.
Progress0 / 4 steps
1
Import the image file
Create a variable called productImage that imports the image file located at ../assets/product.jpg using import from astro:assets.
Astro
Hint

Use import productImage from 'astro:assets'; and then import the image file.

2
Optimize the image with fixed width
Create a variable called optimizedImage that calls productImage as a function with an object setting width to 300.
Astro
Hint

Call productImage as a function with { width: 300 } to optimize.

3
Render the optimized image in HTML
Add an <img> tag that uses optimizedImage.src as the src attribute and optimizedImage.width as the width attribute. Set the alt attribute to "Product image".
Astro
Hint

Use <img src={optimizedImage.src} width={optimizedImage.width} alt="Product image" /> to display the image.

4
Export the Astro component
Add export default before the component code to export it as the default Astro component.
Astro
Hint

Wrap the <img> in an arrow function and export it as default.