如何在Vite构建中使用公共目录

5
在我使用 Vite (^2.9.7) 的项目中,我有一个在 root 目录下的 public 文件夹,其中包含一些图片。
我正在使用 Vite 的 import.meta.glob 函数导入这些图片,例如:
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>
  );
}

在本地运行时,它能够正常工作,但是有一个让人烦恼的警告,提示删除 /public
files in the public directory are served at the root path.
Instead of /public/home/1.png, use /home/1.png.

但是如果将其删除,图像就无法正常工作。

但主要的问题是在构建和部署项目时,public文件夹不存在并且所使用的路径也无法正常工作,但如果在开发工具中更改src路径,则它可以正常工作...

输入图像描述信息

我是否漏掉了某些配置?

1个回答

1

你不能使用 Object.keys(),因为它总是返回绝对路径。相反,使用 Object.values()

你可以将 {eager: true,import: 'default'} 作为 Glob Import 的第二个参数传递,这样返回值将只是资源的公共 URL。

你的代码将如下所示。

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>
  );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接