Skip to content

Instantly share code, notes, and snippets.

@tkon99
Created October 6, 2021 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkon99/55b7574e2cce5926f14a623639656ba0 to your computer and use it in GitHub Desktop.
Save tkon99/55b7574e2cce5926f14a623639656ba0 to your computer and use it in GitHub Desktop.
An example implementation of an Astro image component that retrieves an image from a given url, stores it locally and generates an img tag referring to the local copy.
---
/* Demo implementation of an Astro image component that
fetches a remote image and stores it locally, so it is
hosted on the same platform.
Can be expanded to generate srcset images for different
screen sizes and/or compress images for good Lighthouse
scores.
My usecase: using Notion as my CMS and saving thumbnails
locally with the rest of the project.
Note: uses built-in node module fs, discouraged by Astro
Example usage:
import Image from '../components/ImageComponent.astro';
<Image src={image} css_class="rounded-t-lg"/>
Where image is a remote url
*/
import { promises as fs } from 'node:fs';
const fileExists = async path => !!(await fs.stat(path).catch(e => false));
let {filename = false, src = false, alt = "", css_class = ""} = Astro.props;
// If no filename is given, extract from url (semi-specific to my usecase)
if(filename == false){
filename = src.split('?')[0].split('/');
filename = filename[filename.length - 1];
}
// Filename to be used in img tag (i.e. what the user sees)
const local_image = "/astro_img/"+filename;
// If file does not exist, fetch and save
if(!(await fileExists('public/astro_img/'+filename))){
const image_file = await fetch(src);
const image_data = await image_file.arrayBuffer();
await fs.writeFile('public/astro_img/'+filename, new Buffer(image_data));
}
---
<img src={local_image} class={css_class} alt={alt}/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment