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

Is dynamic import even possible?

MelleNi opened this issue · comments

commented

I'm trying to dynamically import images, like so:

const imageUrl = (await import(src)).default where src is ../images/image.jpg

But I get a svite error:

The above dynamic import cannot be analyzed by Vite.
See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supported dynamic import formats. If this is intended to be left as-is, you can use the /* @vite-ignore */ comment inside the import() call to suppress this warning.

Coupled with:

  props.src = props.src.replace(search, "");

Even when I try this:

import imageUrl from "../images/image.jpg";

I get an error:

TypeError: props.src.replace is not a function
    at Module.getFilteredProps 

How do I dynamically import images?

Create a helper function to handle the dynamic import and return the image URL as a string:
async function importImage(src) {
const module = await import(src);
return module.default;
}

Call the helper function and pass the image source as a parameter:
const imageUrl = await importImage("../images/image.jpg");

or use
Use the require function instead of the import statement to dynamically import the image:

commented

Create a helper function to handle the dynamic import and return the image URL as a string: async function importImage(src) { const module = await import(src); return module.default; }

Call the helper function and pass the image source as a parameter: const imageUrl = await importImage("../images/image.jpg");

or use Use the require function instead of the import statement to dynamically import the image:

When I call it normally, it works, but for some reason only with /src/ and not with ../ (the official astro image component does work with the dots):

<Picture
src="/src/images/file.jpg"
/>

But when I try your method, or

export interface Props {
	url: string;
    alt: string;
    caption: string;
}
const { url, alt, caption } = Astro.props;
const imageUrl = (await import(url)).default

I get the error:
Input file is missing

Edit: maybe noteworthy that I don't get the original error from my first post any longer

Opph - I've just run into this trying to render an image from getImage().

However, we can rely on ./src/images as the basis of our path to transform what getImage() gives us.

---
import yourImage from '../images/your-image.jpg' 

const src = decodeURIComponent(yourImage.src)
  .replace(/.*\/src\//, './src/')    // remove root path
  .replace(/\?.*$/, '')                 // remove prams
---

<>
    <Img src={src} width="200" alt="test" />
</>