Angular2 + webpack不显示图像

时间:2017-03-02 07:56:18

标签: angular webpack

我已关注Angular2 webpack tutorial,但似乎该应用无法加载任何图片。这是我的应用程序的目录结构:

...

/dist/
/src/assets/images/
/src/assets/css/

...

这是文件 config / webpack.common.js 上的webpack配置:

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');

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

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

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

  plugins: [
    // Workaround for angular/angular#11580
    new webpack.ContextReplacementPlugin(
      // The (\\|\/) piece accounts for path separators in *nix and Windows
      /angular(\\|\/)core(\\|\/)(esm(\\|\/)src|src)(\\|\/)linker/,
      helpers.root('./src'), // location of your src
      {} // a map of your routes
    ),

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

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

现在,如果我尝试将一些图像添加到模板中:

<img src="/assets/images/hp-logo.png">

我在编译期间(运行npm start时)总是收到以下错误:

ERROR in ./src/app/templates/dashboard.component.html
Module not found: Error: Can't resolve './assets/images/hp-logo.png' in '/frontend/src/app/templates'
 @ ./src/app/templates/dashboard.component.html 1:582-620
 @ ./src/app/components/dashboard.component.ts
 @ ./src/app/modules/app.module.ts
 @ ./src/main.ts
 @ multi (webpack)-dev-server/client?http://localhost:3000 ./src/main.ts

我想这与文件加载器有关,但在尝试不同的配置后,我无法让它工作。

有人可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:4)

您应该编写相对于模板位置的图像路径。如果您的模板是例如在/src/module1/template.html然后你的图像位置应该是

<img src="../assets/images/hp-logo.png">

答案 1 :(得分:3)

尝试添加:

 new CopyWebpackPlugin([{
     from: 'src/assets',
     to: 'assets',
 }, {
     from: 'src/meta',
 },])

到plugins数组中的webpack.common.js。