RafidMuhymin / astro-imagetools

Image Optimization tools for the Astro JS framework

Home Page:astro-imagetools-docs.vercel.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

I created a Svelte Img component

silveltman opened this issue Β· comments

πŸŽ‰ I created a svelte Img component πŸŽ‰

How to use

Use the renderImg() APIin a parent .Astro component/page/layout, to get the html for the img. Then pass the html as a prop to the component.

Advantages of this component

It allows you to set attributes directly on the component, instead of via the API. This means you can set classes and sizes in you svelte components, instead of the parent .Astro component/page/layout.

I think this is great because those 2 attributes are depended on the design.

As for the src and alt, I personally don't mind having to set these in the .Astro component/page/layout. I have all my website in markdown files anyway, since that integrates best with my git-based CMS (CloudCannon)

Any tips?

Please let me know :)

Parent.astro

---
import { renderImg } from 'astro-imagetools/api'
import Img from '@components/imagetools/Img.svelte'


const { img } = await renderImg({
  src: 'https://picsum.photos/1024/768',
  alt: 'A random image',
})
---

  <Img {img}   />

Img.svelte

<script lang="ts">
  export let img: String
  // export let link: String
  // export let style: String

  let className = ''
  export { className as class }
  export let sizes: String = ''

  function findBetween(str, start, end) {
    const startIndex = str.indexOf(start) + start.length
    const endIndex = str.indexOf(end, startIndex)
    return str.substring(startIndex, endIndex)
  }

  function replace(attribute, value) {
    const currentValue = findBetween(img, `${attribute}="`, '"')
    img = img.replace(currentValue, value)
  }

  if (className) replace('class', className)
  if (sizes) replace('sizes', sizes)
</script>

{@html img}
commented

That's actually sort of clever.