serlingpa February 2016

Very simple: requiring images in webpack and Angular 2

I am having some trouble requiring images in my Angular 2 webpack applicaiton.

I have tried three or four image loaders but I don't seem to be able configure them properly and the result in the HTML is incorrect.

For example, at the moment I have:

<img src='${require("../images/logo.png")}'>

The file containing this image is part of a template which is required like this:

@Component({
    selector: 'appstore-app',
    directives: [ ...ROUTER_DIRECTIVES ],
    styles: [require('../sass/appstore.scss').toString()],
    template: require('./app.component.html')
})

This results in an error in the browser:

GET: http://localhost:8080/$%7Brequire(%22../images/logo.png%22)%7D 

My loader for images image my webpack.config.js looks like this:

{ test: /\.(png|jpg|gif)$/, loader: "url-loader?limit=50000&name=[path][name].[ext]" }

I may well be muddling syntaxes here but as I've said I've tried a few methods. This doesn't work. The $require makes it into the HTML verbatim without being transformed!

How do I either copy the images to the build folder or package them as a DataURL?

Please help!

Answers


serlingpa February 2016

Found the answer.

There's no need to $require the src in the image; webpack will handle this with the right loader.


Arun Abraham February 2016

I did not proof check this, but this is the general idea:

Require it to a variable in the respective controller in the following manner

$scope.imageSrc = require('../images/logo.png');

And then in your template, the imageSrc would either be base64 encoded or the data url as per your loader config.

<img src='{{imageSrc}}'>

Post Status

Asked in February 2016
Viewed 3,018 times
Voted 12
Answered 2 times

Search




Leave an answer