Reference file in public folder from CSS in create-react-app

怎甘沉沦 提交于 2020-12-01 02:35:38

问题


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

You attempted to import example.png which falls outside of the project src/ directory

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.

Edit: 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.


回答1:


Just use a / before the name, this will make it relative to the build output root, which includes anything in the public folder.

so for the question asked above:

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

the critical part being

/example.png 

refers to a file, example.png, that is in the public folder




回答2:


Remove the extra .. in the relative path. :)




回答3:


In my case, to access the images from css/scss, had to move the images directory as well as fonts, to the src directory. After which i was able to refer them in the css/scss files directly,

 background-image: url("/images/background.jpg");

references:

https://github.com/facebook/create-react-app/issues/829

https://create-react-app.dev/docs/using-the-public-folder/



来源:https://stackoverflow.com/questions/48841775/reference-file-in-public-folder-from-css-in-create-react-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!