创建React App 4.0无法解析公用文件夹中的图像路径 [英] Create React App 4.0 cannot resolve image path in public folder

查看:91
本文介绍了创建React App 4.0无法解析公用文件夹中的图像路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经升级到最新的Create React App 4.0.现在, scss 无法解析公用文件夹中的图像资产.我之前使用的是CRA 3.4.1.效果很好.

I have upgraded to the latest Create React App 4.0. Now the scss cannot resolve image assets in the public folder. I was using CRA 3.4.1 before. It worked fine.

有什么想法吗?我不想使用 npm弹出

Any ideas? I don't want to use npm eject

icon.svg位于 public/images

The icon.svg is in public/images

背景图片:url(/images/icon.svg);

Failed to compile.

./src/Components/style.scss 
(./node_modules/css-loader/dist/cjs.js??ref--5-oneOf-6-1!
./node_modules/postcss-loader/src??postcss!
./node_modules/resolve-url-loader??ref--5-oneOf-6-3!
./node_modules/sass-loader/dist/cjs.js??ref--5-oneOf-6-4!
./src/Components/style.scss)
Error: Can't resolve '../../../../../../icon.svg' in ''

在Create React App 3.x中,引用(S)CSS中的公用文件夹,只需使用开始斜杠即可,这已经在此处回答.

In Create React App 3.x, referencing an image from the public folder in (S)CSS worked by simply using a starting slash, as has been been answered here.

正如OP所解释的,该图像位于 public/images 中,并被引用为 url(/images/icon.svg).

As the OP has explained, the image is in public/images and is being referenced as url(/images/icon.svg).

这在Create React App 4.0.0中不再起作用,并给出错误消息错误:无法解析'../../../../../../icon.创建React应用的更改日志未提及有关公用文件夹的重大更改.

This doesn't work in Create React App 4.0.0 anymore and gives the error message Error: Can't resolve '../../../../../../icon.svg' in ''. The changelog of Create React App doesn't mention a breaking change regarding the public folder.

推荐答案

作为临时的解决方法,您可以将图像移动到 src/中,直接将它们导入组件中. import myImage from'../file.svg'并设置 style = {{backgroundImage:file}}> ?

As a temporary workaround, you could move the images into src/, import them directly in the components import myImage from '../file.svg' and set style={{ backgroundImage: file }}>?

这篇关于创建React App 4.0无法解析公用文件夹中的图像路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆