我正在加载带角度的图像,例如
<img ng-src="{{::path-to-image}}"/>
当我使用webpack捆绑我的应用程序时,图像URL在运行时被解析,因此不会被webpack的加载器捆绑 .
这是我正在使用的图像加载器:
{ test: /\.(jpe?g|png|gif|svg)$/i, loader: 'url?limit=8192!img' }
webpack如何捆绑运行时解析的那些图像?
因为我也需要这样的功能,并且发现原始答案远非一个完美的解决方案,我最终自己搞清楚了 .
在控制器中写一个函数:
$scope.loadImage = function(image) { return require('/images/' + image); };
并在你的ng-src中使用它:
<img ng-src="{{loadImage('myImage')}}" />
之后,为了使动态需要工作,你可以使用context .
例如:https://github.com/webpack/webpack/tree/master/examples/require.context#examplejs
如果您需要以编程方式生成的图像路径,则意味着您有一些逻辑期望此图像存在 . 换句话说,您应该将此图像视为该逻辑的依赖关系,因此您需要明确地要求它 .
在你的JS代码中(例如:controller)
this.imageUrl = require('path-to-image' + someDynamicValue + '.jpg');
在您的模板中:
<img ng-src="{{::myCtrl.imageUrl}}"/>
Webpack足够聪明,可以理解动态 require 语句并捆绑与该表达式匹配的图像 . 查看文档以获取更多详细信息:https://webpack.github.io/docs/context.html)
require
我创建了 uiImage 指令 requires 图像 .
uiImage
requires
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;
用法:
<img ui-image='myimage.png' />
webpack.config.js
我有一个Webpack解析 Images ,它指向我所有图像的位置 .
Images
resolve: { alias: { 'Images': path.join(config.appDir, '/images') } }
我需要在运行时使用webpack生成的哈希动态解析图像,例如 imgA.bd79a5ba.png .
imgA.bd79a5ba.png
{ test: /\.png$/, loader: 'file-loader?name=images/[name].[hash].[ext]', }
我最终创建了一个别名模块并需要图像:
let map = { 'imgA': require('./images/imgA.png'), 'imgB': require('./images/imgB.png'), 'imgC': require('./images/imgC.png') }
这会产生 Map :
{ 'imgA': imgA.bd79a5ba.png, 'imgB': imgB.e51f66a2.png, 'imgC': imgC.d84ae37c.png }
在我的组件中,我从 Map 中解析了网址:
self.link = function link(scope) { scope.imageUrl = function(name) { function return map[name]; } };
然后加载图像是微不足道的:
<img ng-src="{{ imageUrl('imgA') }}">
以上是简化的 . 我发现为 Map 创建模块很有用:
export default { 'imgA': require('./images/imgA.png'), 'imgB': require('./images/imgB.png'), 'imgC': require('./images/imgC.png') }
然后将其导入组件模块:
import urlMap from './imageUrlMap' console.log(urlMap.imgA) > imgA.bd79a5ba.png
4 回答
因为我也需要这样的功能,并且发现原始答案远非一个完美的解决方案,我最终自己搞清楚了 .
在控制器中写一个函数:
并在你的ng-src中使用它:
之后,为了使动态需要工作,你可以使用context .
例如:https://github.com/webpack/webpack/tree/master/examples/require.context#examplejs
如果您需要以编程方式生成的图像路径,则意味着您有一些逻辑期望此图像存在 . 换句话说,您应该将此图像视为该逻辑的依赖关系,因此您需要明确地要求它 .
在你的JS代码中(例如:controller)
在您的模板中:
Webpack足够聪明,可以理解动态
require
语句并捆绑与该表达式匹配的图像 . 查看文档以获取更多详细信息:https://webpack.github.io/docs/context.html)我创建了
uiImage
指令requires
图像 .用法:
webpack.config.js
我有一个Webpack解析
Images
,它指向我所有图像的位置 .我需要在运行时使用webpack生成的哈希动态解析图像,例如
imgA.bd79a5ba.png
.我最终创建了一个别名模块并需要图像:
这会产生 Map :
在我的组件中,我从 Map 中解析了网址:
然后加载图像是微不足道的:
以上是简化的 . 我发现为 Map 创建模块很有用:
然后将其导入组件模块: