来自create-react-app中CSS的公用文件夹中的参考文件 [英] Reference file in public folder from CSS in create-react-app

查看:59
本文介绍了来自create-react-app中CSS的公用文件夹中的参考文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用creat-react-app(CRA),只是想通过CSS将一个png文件放置在公共文件夹中(我将所有图像文件保存在那里).现在,我试图通过CSS引用此图像(我只在新生成的CRA应用中添加了 background-image 行):

I am using creat-react-app (CRA) and simply want to include a png file placed in the public folder via CSS (I keep all image files there). Now I am trying to reference this image via CSS (I only added the background-image line to a freshly generated CRA app):

.App-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
  background-image: url("../public/example.png");
}

您尝试导入example.png文件,该文件不在项目src/目录中

如何在不复制/src 内部某处的情况下,从CSS文件中引用图像文件?我也不想弹出应用程序并摆脱错误消息.

How do I reference the image file from within the CSS-file without copying somewhere inside /src? I also don't want to eject the application and get rid of the error message.

该问题与 create-react-app导入src目录之外的限制不同,因为它没有显示如何在CSS级别解决此问题.提议的解决方案是在我不想执行的JavaScript文件中添加样式.

This question is different from The create-react-app imports restriction outside of src directory because it does not show how to solve this problem at a CSS level. The proposed solution is to add the style inside the JavaScript file which I don't want to do.

推荐答案

只需在名称前使用/,这将使其相对于输出根,包括公共文件夹中的所有内容((如果完成的托管应用程序在域的根目录中提供).

Just use a / before the name, this will make it relative to the output root, which includes anything in the public folder (provided the finished hosted application is served at the root of a domain).

对于上述问题:

.App-header {
  background-color: #222;
  height: 150px;
  padding: 20px;
  color: white;
  background-image: url("/example.png");
}

关键部分是

/example.png 

指的是example.png文件,该文件位于公共文件夹中(在根目录下提供)

refers to a file, example.png, that is in the public folder (served at the root level)

也可以是相对的:

一个人也可以使用

./example.png

假设css文件也是从public/build目录中导入的,则该文件是相对于css文件的,并且不依赖于在域根目录中的投放,但通常在CRA webpack中将CSS捆绑在一起,或者可能无法从该位置加载.(您可以使用带有%PUBLIC_URL%/Styles.css 宏的rel标签直接将其导入html文件中)

provided that the css file was also imported from the public/build directory, this would be relative to the css file and not depend on being served at the domain root, but typically in CRA webpack will bundle the CSS and it may or may not be loaded from this location. (you could import it in the html file directly using rel tag with the %PUBLIC_URL%/Styles.css macro)

这篇关于来自create-react-app中CSS的公用文件夹中的参考文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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