I'm using es6 and want to import an image to use with webpack. Looking at the file-loader doc, this is the example they gave:
var url = require("file!./file.png");
url will now return something like /static/351f9446b3ba577b6a79e373e074d200.png
This works with require, but how do I use import
to do this, I've tried -
import * as url from '../images/151.png';
but that doesn't work because url remains undefined. How do I set a variable to what I'm importing when it's an image?
To import and use an image in a React component:Import the local image, e.g. import MyImage from './thumbnail. webp'; . Pass the imported image to the src prop on the img element. For example, <img src={MyImage} alt="horse" /> .
import * as url from '../images/151.png';
but that doesn't work because url remains undefined. How do I set a variable to what I'm importing when it's an image?
Using Webpack 2.0 with file-loader plugged-in. It works in my case, but import returns something like object bytemap instead of data-uri string;
And this object has the 'default' property, that contains the same data, as if it was required.
Honestly I'm not sure what is that object, and why there is the default property but that's how I've made it work.
import '../css/bootstrap.css'; import '../css/app.scss'; import * as url from '../images/webpack_logo.png'; let img = document.createElement('img'); img.style = { height: '25%', width: '25' }; debugger; img.src = url.default; console.log('imported', url); document.getElementById('img_container').appendChild(img);
The way mentioned in previous answer returned undefined, btw. And it's expected, because that syntax relies on default export to be declared on the source module.
Use
import url from "file!./file.png"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With