6

In my project using Vite (^2.9.7) I have a public folder in my root directory which contains some images.

I'm importing the images using Vite's import.meta.glob function, e.g.

import { LazyBlock } from "../LazyBlock";

const images = import.meta.glob("./home/*.(jpg|png|jpeg)");

export function Gallery() {
  const blockImages = Object.keys(images);

  return (
    <div className="flex justify-center w-full">
      <div className="flex flex-wrap justify-center min-h-8">
        {blockImages.map((image, index) => (
          <LazyBlock url={image} key={index} />
        ))}
      </div>
    </div>
  );
}

While running in localhost, it works perfectly but there's an annoying warning saying to remove the /public:

files in the public directory are served at the root path.
Instead of /public/home/1.png, use /home/1.png.

But removing it, the images stop working.

But the main problem is when I build and deploy the project, the public folder stop existing and the route used stop working, but if change the src path in devtools, it simply works...

enter image description here

There's some configuration am I missing?

1 Answer 1

1

You can't use the Object.keys() since it will always return the absolute path. Instead use Object.values().

You can pass {eager: true,import: 'default'} for the second argument of the Glob Import, so that the return values will just be the public URL of the assets.

You code will look like this.

import { LazyBlock } from "../LazyBlock";

const images = import.meta.glob("./home/*.(jpg|png|jpeg)", {eager: true,import: 'default'});

export function Gallery() {
  const blockImages = Object.values(images);

  return (
    <div className="flex justify-center w-full">
      <div className="flex flex-wrap justify-center min-h-8">
        {blockImages.map((image, index) => (
          <LazyBlock url={image} key={index} />
        ))}
      </div>
    </div>
  );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.