Created
October 6, 2021 16:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
/* 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