【问题标题】:Very simple: requiring images in webpack and Angular 2非常简单:需要 webpack 和 Angular 2 中的图像
【发布时间】:2016-02-08 19:11:17
【问题描述】:

我在 Angular 2 webpack 应用程序中需要图像时遇到了一些问题。

我尝试了三四个图像加载器,但我似乎无法正确配置它们,并且 HTML 中的结果不正确。

例如,目前我有:

<img src='${require("../images/logo.png")}'>

包含此图像的文件是模板的一部分,需要这样:

@Component({
    selector: 'appstore-app',
    directives: [ ...ROUTER_DIRECTIVES ],
    styles: [require('../sass/appstore.scss').toString()],
    template: require('./app.component.html')
})

这会导致浏览器出错:

GET: http://localhost:8080/$%7Brequire(%22../images/logo.png%22)%7D 

我的图像加载器图像我的 webpack.config.js 看起来像这样:

{ test: /\.(png|jpg|gif)$/, loader: "url-loader?limit=50000&name=[path][name].[ext]" }

我可能在这里混淆了语法,但正如我所说的,我已经尝试了一些方法。这行不通。 $require 无需转换就可以逐字转换为 HTML!

如何将图像复制到构建文件夹或将它们打包为 DataURL?

请帮忙!

【问题讨论】:

  • 你解决了吗?怎么样?

标签: javascript angular webpack


【解决方案1】:

你应该这样做。我知道你想通了,但为了将来参考,你不需要使用 require;改用____Url。 Require 导致我使用 webpack 加载资产的其他库出现问题....不需要。

     <img src="../images/logo.png">

//note styleUrl and templateUrl since you have a path not inline with component
        @Component({
            selector: 'appstore-app',
            directives: [ ...ROUTER_DIRECTIVES ],
            styleUrl: ['../sass/appstore.scss'],
            templateUrl: './app.component.html'
        })

【讨论】:

    【解决方案2】:

    例如

    <img src={{appstore-logo}}>
    

    你的组件代码是

    @Component({
        selector: 'appstore-app',
        directives: [ ...ROUTER_DIRECTIVES ],
        styles: [require('../sass/appstore.scss').toString()],
        template: require('./app.component.html')
    })
    export class AppStoreComponent {
        private appStoreImage: any = require('../images/logo.png');
    }
    

    您必须在应用此组件之前插入此代码。

    declare function require(name: string): string;
    

    您的 AppModule 中的此代码

    如果有更好的方法,请告诉我。

    【讨论】:

      【解决方案3】:

      找到答案了。

      不需要$require图片中的src; webpack 将使用正确的加载器来处理这个问题。

      【讨论】:

      • 我创建了一个额外的webpack.config.js 并尝试为jpe?g|png\gif 引用一个url-loader,它不会自动base64 为&lt;img src=...。我已经花了好几个小时来处理它。如果有人有想法,将不胜感激。
      【解决方案4】:

      我没有对此进行验证,但这是一般的想法:

      通过以下方式将其应用于相应控制器中的变量

      $scope.imageSrc = require('../images/logo.png');
      

      然后在您的模板中,imageSrc 将根据您的加载程序配置进行 base64 编码或数据 url。

      <img src='{{imageSrc}}'>
      

      【讨论】:

      • Angular 2 中没有 $scope
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多