yeoman/grunt-usemin

usemin does not replace the image when the path is generated in js

Opened this issue · 1 comments

I an using AngularJS to build my site. I have an array of assets/images/?.png where ? is generated via _.range as follows:

$scope.model.fad = 'assets/images/' + _.range(1, 6).map(function (e) {return e + '.png';})[_.random(4)];

It works in development environment, but fails in production environment because it tries to find the original one not the usemin generated one.

usemin does not change the <img ng-src="{{model.fad}}"> tag. So how can I fix it?

@chenweiyj the problem is that usemin has no way to know the path of a dynamic image.

One solution I've found with to this problem is to use a map in your code and use this map in your code.

If I'm correct:

$scope.model.fad = 'assets/images/' + _.range(1, 6).map(function (e) {return e + '.png';})[_.random(4)];

could be written :

var images = [
  'assets/images/1.png',
  'assets/images/2.png',
  'assets/images/3.png',
  'assets/images/4.png',
  'assets/images/5.png',
  'assets/images/6.png'
]
$scope.model.fad = images[_.random(4)];

You will need to add a regex for js type in usemin configuration to search for png.

BTW it would also be more performant as you will build the array only one time. If you call this line multiple time, in your version, you're build a new array each time.