I have read a lot of posts on getting image from the public folder with Webpack. However, is there anyway to do so without a Webpack?
My code structure:
./public/logo.png
./src/../source_file.js (which renders an <img> and that needs to be pointed to the logo image
I tried import img from './logo.png'
but that is not working. Also tried relative path but reactjs is preventing me from importing anything outside src
folder.
I have read a lot of posts on getting image from the public folder with Webpack. However, is there anyway to do so without a Webpack?
My code structure:
./public/logo.png
./src/../source_file.js (which renders an <img> and that needs to be pointed to the logo image
I tried import img from './logo.png'
but that is not working. Also tried relative path but reactjs is preventing me from importing anything outside src
folder.
-
1
Are you using Create React App? All the assets in the
public
directory will be available at the root, so you can write<img src="/logo.png" />
– Tholle Commented Jul 24, 2018 at 18:37 -
@Tholle Is it? I'm using a Create React App but still uses that
../../IMAGE-NAME
(which I never like). :D – Radix Commented Jul 24, 2018 at 18:52 -
1
Yes, try to put
logo.png
in directly in thepublic
directory and use<img src="/logo.png" />
to see it in effect. Thepublic
folder will also be copied into thebuild
folder with the build script, so it will work in production as well. – Tholle Commented Jul 24, 2018 at 18:57 -
1
@AtulKhanduri Importing them with Webpack with
../../IMAGE-NAME
is remended, but there is nothing stopping you from keeping an image in the same folder as a ponent, if only that ponent uses the image, for example. Then you can just write./IMAGE-NAME
. But for use cases when that is not appropriate, you can put them in thepublic
folder. – Tholle Commented Jul 24, 2018 at 19:08 - 1 @Tholle The only issue is if the image is shared across several ponents then we have to place it outside of that folder (where ponent is placed). Anyways, thanks for your answers. – Radix Commented Jul 24, 2018 at 19:12
2 Answers
Reset to default 2As long as your package.json is at the root, this will work:
import logo from '../../public/logo.png';
const MyComponent = () => (<div>
<img src={logo} alt={"logo"} />
</div>);
export default MyComponent;
Otherwise, assuming you are copying your /public
folder to the root of your webserver, you can also simply do <img src="/logo.png" alt="logo">
I finally use window.location.origin + "logo.png"
. Posted here in case anyone want to have a try.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745306836a4621760.html
评论列表(0条)