Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use es6 import for images

Tags:

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?

like image 568
stackjlei Avatar asked Sep 12 '16 20:09

stackjlei


People also ask

How do I import an image into react?

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" /> .


2 Answers

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.

like image 82
Aleksej Shovgenja Avatar answered Nov 05 '22 10:11

Aleksej Shovgenja


Use

import url from "file!./file.png"

like image 38
Red Mercury Avatar answered Nov 05 '22 11:11

Red Mercury