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?
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
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)
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')
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With