Webpack 输出错误的图像路径

Webpack outputs wrong path for images

我正在使用 React 和 webpack 构建一个站点。当我使用 webpack 构建应用程序并尝试包含图像时,图像会与其他资产一起写入构建文件夹,但 webpack 输出的图像的 link 不正确。我可以进入 build 文件夹并查看图像,所以它被正确复制了,但 link 是错误的。

我的 React 组件如下所示:

'use strict';

var React = require('react');
var newsFeedIcon = require('../../img/news-feed-icon.png');

//create story component
module.exports = React.createClass({
  render: function () {
    return (
        <div className="col_12 footer-right mobile-foot">
        <img src={newsFeedIcon} />
        <p><a href="/about">About Us</a> | <a href="/contact">Contact Us</a> | <a href="/faq">FAQ</a> | <a href="/media">Media</a> | <a href="#">Privacy Statement</a> | <a href="#">Terms of Service</a></p>
      </div>
      );
  }
})

我的 Webpack 配置如下所示:

    webpack: {
      client: {
        entry: __dirname + '/app/js/client.jsx',
        output: {
          path: 'build/',
          file: 'bundle.js'
        },
        module: {
          loaders: [
          {
            test: /\.jsx$/,
            loader:'jsx-loader'
          },
          {
            test: /\.css$/,
            loader: "style-loader!css-loader"
          },
          {
            test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
            loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
          },         
          { 
            test: /\.jpe?g$|\.gif$|\.png$/i, 
            loader: 'file-loader' 
          },
          {
            test: /\.jpg/,
            loader: 'file'
          }]
        }
      },
      test: {
        entry: __dirname + '/test/client/test.js',
        output: {
          path: 'test/client/',
          file: 'bundle.js'
        },
        module: {
          loaders: [
          {
            test: /\.jsx$/,
            loader:'jsx-loader'
          }] 
        }
      },
      karma_test: {
        entry: __dirname + '/test/karma_tests/test_entry.js',
        output: {
          path: 'test/karma_tests/',
          file: 'bundle.js'
        },
        module: {
          loaders: [
          {
            test: /\.jsx$/,
            loader:'jsx-loader'
          }]
        },
        background: true
      }
    },

从昨天开始我就一直在用头撞墙,所以任何帮助都将不胜感激。让我知道您需要更多信息。

谢谢!

您可以尝试为文件加载器设置 name 选项,以及 output.publicPath.

 output: {
     path: 'build/',
     file: 'bundle.js',
     publicPath: '/assets'
}

...

{ 
     test: /\.(png|jpg)$/, 
     loader: 'file-loader?name=/img/[name].[ext]' 
}

那么你的需求中解析的 url 将是:

/assets/img/news-feed-icon.png