简体   繁体   English

如何修复图像导入时的生产 404 错误

[英]How to fix production 404 error on images' imports

I have a few images on a site that doesn't get loaded.我在一个网站上有一些图片没有加载。 I'm using Vercel and Vite's production preview and both give me this error when importing images:我正在使用 Vercel 和 Vite 的生产预览,并且在导入图像时都给我这个错误:

Failed to load resource: the server responded with a status of 404 ()加载资源失败:服务器响应状态为 404 ()

And, when I reload the page with the browser console open:而且,当我在浏览器控制台打开的情况下重新加载页面时:

GET https://nicole-tongu.vercel.app/src/assets/images/nicole_pic.jpeg 404获取https://nicole-tongu.vercel.app/src/assets/images/nicole_pic.jpeg 404

Here's how I have been importing them:这是我导入它们的方式:

<div className="ms-3 home-image-container">
    <img
       src="/src/assets/images/nicole_pic.jpeg"
       className="home-image"
     ></img>
</div>

When running the code locally, all images' imports work, but I don't know how to make them appear on production.在本地运行代码时,所有图像的导入工作,但我不知道如何让它们出现在生产中。

You can see all my code on GitHub and the app can be found on Vercel您可以在GitHub上看到我的所有代码,该应用程序可以在Vercel上找到

I fixed it in and I sent out a pull request to your github.我修复了它并向您的 github 发送了一个pull request you can visit the result here你可以在这里访问结果

details:细节:

I pull your repository, and run npm run dev ... it works well.我拉你的存储库,并运行npm run dev ... 它运行良好。 image loaded.图像加载。 but when I build your app( npm run build ) and run npm run preview to show the built version of your app, it doesn't work(the image doesn't show in browser like vercel).但是当我构建您的应用程序( npm run build )并运行npm run preview以显示您的应用程序的构建版本时,它不起作用(图像不会显示在像 vercel 这样的浏览器中)。 why?为什么? because there was no image in dist directory.因为dist目录中没有图像。

to load images in vite build version, you should have imported them in the header of your home.jsx like this:要在vite构建版本中加载图像,您应该将它们导入 home.jsx 的home.jsx中,如下所示:

import CallButton from '../components/CallButton'
import '../assets/styles/home.css'

// add this one in your header
import NicoleImage from '../assets/images/nicole_pic.jpeg'

function Home() {
  return (
    <section
      id="home"
      className="bg-primary text-dark p-5 d-flex caixa-responsiva align-items-center"
    >
.
.
.
//rest of your code
.
.
.

and after that, you should inject NicoleImage variable to your src attribute of your <img tag, like this:之后,您应该将NicoleImage变量注入到<img标签的src属性中,如下所示:

          <img
            src={NicoleImage}
            className="home-image"
          />

to sure that it works, run npm run build and see that image file is exist in dist directory, and for seeing the result, run npm run preview command to sure it works on the production为了确保它工作,运行npm run build并查看图像文件存在于dist目录中,为了查看结果,运行npm run preview命令以确保它在生产中工作

after these steps, you can deploy it on vercel完成这些步骤后,您可以将其部署在vercel

good luck祝你好运

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

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