Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading ng-src images with webpack

I am loading an image with angular, e.g.

<img ng-src="{{::path-to-image}}"/>

When I bundle my application with webpack the image URL is resolved in runtime, thus not bundled by webpack's loaders.

This is the image loader I am using:

  {
    test: /\.(jpe?g|png|gif|svg)$/i,
    loader: 'url?limit=8192!img'
  } 

How can webpack bundle those images resolved in runtime?

like image 393
Eitan Peer Avatar asked Dec 23 '15 13:12

Eitan Peer


3 Answers

Because I also needed thus functionality and found the original answer was far from a perfect solution I ended up figuring it out on my own.

Write a function in the controller:

$scope.loadImage = function(image) {
    return require('/images/' + image);
};

And use it in your ng-src:

<img ng-src="{{loadImage('myImage')}}" />

After that to make dynamic requires work you can use a context.

For example: https://github.com/webpack/webpack/tree/master/examples/require.context#examplejs

like image 196
Lakatos Gyula Avatar answered Oct 30 '22 12:10

Lakatos Gyula


If you need an image path that is programmatically generated, it means you have some logic expecting this image to exist. In other words, you should consider this image as a dependency of that piece of logic, thus you need to require it explicitely.

In your JS code (eg: controller)

this.imageUrl = require('path-to-image' + someDynamicValue + '.jpg');

In your template:

<img ng-src="{{::myCtrl.imageUrl}}"/>

Webpack is smart enough to understand the dynamic require statement and bundle your images that will match that expression. Check the documentation for more details: https://webpack.github.io/docs/context.html)

like image 42
gonzoyumo Avatar answered Oct 30 '22 13:10

gonzoyumo


I created a uiImage directive which requires the images.

 function uiImage() {
    return {
      restrict: 'A',
      link: function(scope, element, attr) {
        var src = attr.uiImage || attr.src;

        function loadImage(image) {
          return require(`Images/${image}`);
        }

        // required for webpack to pick up image
        element.attr('src', loadImage(src));
      }
    };
  }

  uiImage.$inject = [];
  export default uiImage;

Usage:

<img ui-image='myimage.png' />

webpack.config.js

I have a Webpack resolve Images which points to the location of all my images.

resolve: {
  alias: {
   'Images': path.join(config.appDir, '/images')
  }
}
like image 38
cusejuice Avatar answered Oct 30 '22 14:10

cusejuice