更新到 create-react-app v4,不渲染图像

Updating to create-react-app v4 , not rendering images

我刚更新到 create-react-app v4

所以我更新的依赖项如下所示

"react": "^17.0.1",
"react-dom": "^17.0.1",
"react-scripts": "4.0.0",

我删除了所有 node_modules 文件夹并重新安装了它们

我已将我所有的图像包含在图像文件夹中,该文件夹位于 create-react-appsrc 文件夹中。当我回到 react-scripts 3.4.4 时,我的图像渲染正确,但在 v4.0.0 中图像根本没有渲染。我在我的应用程序中同时使用 pngsvg,但都无法呈现。

编辑: 我发现 public 文件夹中的图像似乎可以毫无问题地呈现。但是我希望我的组件在 src 文件夹中使用的图像仍然不渲染,并且将组件使用的图像放在 src 文件夹中是一个很好的做法。 Do I store Image assets in public or src in reactJS?

您在使用 NODE_PATH 吗?

v4.0.0 中有重大更改。

Removed typescript flag and NODE_PATH support

We've removed the deprecated typescript flag when creating a new app. Use --template typescript instead. We've also dropped deprecated NODE_PATH flag as this has been replaced by setting the base path in jsconfig.json.

如果您正在使用它,请改用 jsconfig.json

尝试更新 require to import 语句。

const myImg = require('../imagepath.jpg')

import myImg from '../imagepath.jpg'

当您的图像 URL 是静态的时,Shyam 的答案有效,但是,如果您希望动态创建 URL,它就不会起作用。

如果是这种情况,您可以使用来自 GitHub 的 answer:

require("../../assets/images/others/"+loginBgImage)

loginBgImage can have different values (login-image.jpg, login-new-image.jpg)

this got fixed using require("../../assets/images/others/"+loginBgImage).default

require 之后的 .default 就可以了。