2016-11-26 100 views
1

我在Angular2中有一个使用Webpack构建和搭建项目的小应用程序。使用Webpack和Angular2生成图像

我所面对的是我无法加载在TypeScript文件中指定的生产的图像。当我运行npm run build时,在生成的文件中没有找到这些图像(生成了在SCSS中指定的图像)。

下面是一个示例,下面是组件的外观,我的Webpack配置看起来非常基本。

主要问题是有可能修复它,也许需要为这个案例添加一些Webpack加载器来处理它,但我没有任何想法成为Webpack的新手。

import { Component, OnInit, Injectable } from '@angular/core'; 

@Injectable() 
@Component({ 
    selector: 'custom-template', 
    templateUrl: './custom.html' 
}) 

export class CustomComponent { 
    public data: any = [ 
     { 
      image: '../../../assets/images/1.jpg', 
      text: 'Text 1...' 
     }, 
     { 
      image: '../../../assets/images/2.jpg', 
      text: 'Text 2...' 
     }, 
     { 
      image: '../../../assets/images/3.jpg', 
      text: 'Text 3...' 
     } 
    ]; 
} 

回答

1

我相信Webpack提供的file-loader是你需要的。当你想包含一个文件时,你可以使用加载程序来请求它,它将返回输出中的相对路径。

npm install --save-dev file-loader 

data那么应该是这样的(提供的路径是相对于您的文件):

public data: any = [ 
    { 
     image: require('file-loader!../../../assets/images/1.jpg'), 
     text: 'Text 1...' 
    }, 
    ... 
]; 

评估时,这会产生这样的事情:

与安装它

public data: any = [ 
    { 
     image: '/project-output-path/abcdef014ea5754463fac.jpg', 
     text: 'Text 1...' 
    }, 
    ... 
]; 
+1

太棒了,它是我正在寻找。 感谢您的帮助,并纠正文中的错误。 –

+0

没问题,很高兴帮助。如果您有任何问题,请随时在此发表评论或者提出其他问题; Webpack可能相当棘手,无法正确使用! – Aurora0001