小编典典

Webpack输出错误的图像路径

reactjs

我正在建立一个带有react和webpack的网站。当我使用webpack构建应用程序并尝试包含图像时,图像与其他资产一起写入了build文件夹,但是webpack输出的图像链接不正确。我可以进入构建文件夹并查看图像,因此正确复制了该图像,这是链接错误。

我的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

      }

    },

从昨天开始,我就一直把头撞在墙上,因此,我们将不胜感激。让我知道您需要更多信息。

谢谢!


阅读 262

收藏
2020-07-22

共1个答案

小编典典

您可以尝试为file-loader以及设置 name 选项output.publicPath

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

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

然后,您的需求中解析的网址将是:

/assets/img/news-feed-icon.png
2020-07-22