29

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?

stackjlei
  • 9,485
  • 18
  • 65
  • 113

4 Answers4

18

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.

Community
  • 1
  • 1
Aleksej Shovgenja
  • 3,502
  • 1
  • 14
  • 12
12

Using file-loader you can achieve this with the nice and simple syntax of:

import youNameIt from "../images/151.png";
creyD
  • 1,972
  • 3
  • 26
  • 55
Tomek
  • 502
  • 6
  • 14
  • 1
    Thanks, but how do you use `youNameIt` within your actual file to display your image on to page? – klewis Mar 21 '19 at 12:49
  • 2
    Well, what you imported is a path to the image so you can use it for example like this: – Tomek Mar 26 '19 at 14:58
11

Use

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

Red Mercury
  • 3,971
  • 1
  • 26
  • 32
  • Are you sure about this ? I got this error : ```Unable to resolve "file!./backgrounds/plan.jpg" from "example/index.js" Failed building JavaScript bundle.``` – Charly Jul 11 '18 at 09:39
4

With webpack 4 & es6 I used:

const url = require('../images/webpack_logo.png');

then used this as the src="url" in my <img> tag.

Aziz
  • 1,584
  • 4
  • 23
  • 43