【问题标题】:Angular 2 and webpack, import images with [src] syntaxAngular 2 和 webpack,使用 [src] 语法导入图像
【发布时间】:2016-07-29 08:55:38
【问题描述】:

我正在尝试在我的 Angular 2 应用程序中导入图片,如下所示:

<img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" />

但是当我使用 [src] 标签时,webpack 不会在我的捆绑项目的输出文件中包含图片。如果我按以下方式包含图片,则一切正常。

<img *ngIf="person.status" src=require('IMAGE_URL') width="20" height="20" />

我的 webpack 配置如下所示(它基于 angular 2 官方文档中的 webpack 教程):

module.exports = {
  entry: {
    'polyfills': './app/polyfills.ts',
    'vendor': './app/vendor.ts',
    'app': './app/main.ts'
  },

  resolve: {
    extensions: ['', '.js', '.ts']
  },

  module: {
    loaders: [
      {
        test: /\.ts$/,
        loaders: ['ts', 'angular2-template-loader']
      },
      {
        test: /\.html$/,
        loader: 'html'
      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
        loader: 'file?name=./assets/[name].[hash].[ext]'
      },
      {
        test:/\.scss$/,
        exclude: /node_modules/,
        loader:'style!css!sass'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        loader: 'raw'
      },
      {
        test:/\.json$/,
        exclude: /node_modules/,
        loader:'json'
      }
    ]
  },

  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: ['app', 'vendor', 'polyfills']
    }),

    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
  ]
};

之所以要使用 [src] 是因为图片在运行时动态变化,并且 url 必须能够变化。有人知道如何配置 webpack 以包含在我的应用程序中导入的带有 [src] 标签的图片吗?

【问题讨论】:

标签: angular webpack


【解决方案1】:

将 require() 语句放在你的组件文件中:

ngOnInit(): void {
    this.IMAGE_URL = require('../../public/images/' + this.imageName + '.png');
}

那么你可以用同样的方式编写你的html:

<img *ngIf="person.status" [src]="{{IMAGE_URL}}" width="20" height="20" />

【讨论】:

    猜你喜欢
    • 2017-10-01
    • 2017-05-10
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-09
    • 2022-01-03
    相关资源
    最近更新 更多