【问题标题】:How to load images from dynamic src in angular2 and webpack?如何从 angular2 和 webpack 中的动态 src 加载图像?
【发布时间】:2017-07-03 18:17:04
【问题描述】:

我在我的项目中使用 angular2 和 webpack2。

我的同事从 Angular2 QuickStart 开始项目,然后我将其移至 Webpack 环境。

我使用html-loader 加载组件模板并使用url-loader 提取图像和字体:

{
    test: /\.html$/,
    loader: 'html-loader'
},
{
    test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
    use: 'url-loader?limit=1000&name=assets/[name].[hash].[ext]'
},

模板是这样的:

<section class="creation-mobile">
    <img src="../../../images/camera/cn/mobile/creation.jpg" alt="" class="img-cn">
    <img src="../../../images/camera/en/mobile/creation.jpg" alt="" class="img-en">
</section>

当我构建它时,Webpack 可以找到图像并将它们导出到asstes/

在我遇到这样的模板之前它工作正常:

<li *ngFor="let i of [1,2,3]" class="item{{i}} m1-view">
    <div class="{{lang}}-video-view">
        <img src="../../../images/os/{{lang}}/medium/one-step{{i}}{{deviceRatio == 1?'':'@2x'}}.jpg">
        <video class="video-medium" preload="auto" src="../../../videos/os/{{lang}}/medium/one-step-{{i}}{{deviceRatio == 1?'':'@2x'}}.mp4" [video-play]="onestepVideoState[i-1]"></video>
        <img src="../../../images/os/{{lang}}/large/one-step{{i}}{{deviceRatio == 1?'':'@2x'}}.jpg">
        <video class="video-large" preload="auto" src="../../../videos/os/{{lang}}/large/one-step-{{i}}{{deviceRatio == 1?'':'@2x'}}.mp4" [video-play]="onestepVideoState[i-1]"></video>
    </div>
    <a class="replay" [innerHTML]="os.replay.title" [ngClass]="{'active': onestepReplayState[i-1]}" (click)="onestepReplay(i-1)"></a>
</li>

../../../images/os/{{lang}}/medium/one-step{{i}}{{deviceRatio == 1?'':'@2x'}}.jpg这样的src包含{{lang}}{{i}}{{deviceRatio == 1?'':'@2x'}}来获取不同的资源,而url-loader不能解析这种url。

我们要散布*ngFor并使用ngif,写大量的&lt;img&gt;标签来导入图片。

有没有办法在angular2和webpack中加载这种url?

Add1:抱歉忘记声明,langdeviceRatio 依赖于浏览器环境,所以构建时值不确定。 lang 的值将是cnen 之一,所以我们要将../../../images/os/en/medium/..xxx.jpg../../../images/os/cn/medium/..xxx.jpg 都加载到最终的dist 目录中。

【问题讨论】:

标签: angular webpack


【解决方案1】:

根据您的构建设置,您可以在 JS 文件中使用 require.context 预先要求图像。

function importAll (r) {
  return r.keys().map(r);
}
var modules = importAll(require.context(directory, useSubdirectories = true, regExp = /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/));

您所做的是 - 递归地要求包含图像的文件夹,它们将在所需的位置可用。 在此处查看更多信息:https://webpack.js.org/guides/dependency-management/#require-context

【讨论】:

    猜你喜欢
    • 2017-12-11
    • 2016-11-05
    • 2016-03-29
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-02-13
    • 2019-03-15
    • 2014-05-16
    相关资源
    最近更新 更多