繁体   English   中英

Vite构建中如何使用public目录

[英]How to use public directory in Vite build

在我使用 Vite ( ^2.9.7 ) 的项目中,我的root目录中有一个public文件夹,其中包含一些图像。

我正在使用 Vite 的import.meta.glob function 导入图像,例如

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

在 localhost 中运行时,它运行良好,但有一个烦人的警告说要删除/public

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

但是删除它,图像停止工作。

但主要问题是当我构建和部署项目时, public停止存在并且使用的路由停止工作,但是如果在 devtools 中更改 src 路径,它就可以正常工作......

在此处输入图像描述

我缺少一些配置吗?

您不能使用Object.keys()因为它总是返回绝对路径。 而是使用Object.values()

您可以为 Glob Import 的第二个参数传递{eager: true,import: 'default'} ,这样返回值将只是资产的公共 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>
  );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM