反应与Webpack:加载图像并将其显示为背景图像

问题描述:

我正在创建一个类似横幅的组件,并将图像设置为组件的背景,但无法正常工作.我尝试了网上发布的其他建议,但没有运气,目前我不确定我的错误是在响应代码内,还是Webpack无法正确加载文件.

I'm creating a banner-like component with image set as a component's background but I can't get it to work. I tried different suggestions posted online to no luck and at the moment I'm not sure whether my mistake is within react code or it's the webpack that doesn't load the files correctly.

这是我的文件结构:

AppFolder
 - client/
 -- components/
 -- data/
 -- images/
 ----- banners/
 ------- frontPageBanner2.png
    ------- 
 -- styles/
 -- myApp.js
 -- store.js
    ---------
 - index.html
 - package.json
 - webpack.config.dev.js

这是我的webpack配置:

Here's my webpack configuration:

var path = require('path'); 
var webpack = require('webpack');

module.exports = {
  devtool: 'source-map',
  entry: [
    'webpack-hot-middleware/client',
    './client/myApp'
  ],
  output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin()
  ],
  module: {
    loaders: [
    // js
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loaders: ['babel'],
      presets: ['es2015', 'react'],
      include: path.join(__dirname, 'client')
    },
    // CSS
    { 
      test: /\.scss$/,
      include: path.join(__dirname, 'client'),
      loader: 'style-loader!css-loader!sass-loader'
    },

    //    PNG
    {
      test: /\.(jpg|png)$/,
      loader: "url-loader?limit=25000",
      //loader: 'file?name=[path][name].[ext]',
      include: path.join(__dirname, 'client')
    },

    // FontAwesome
    { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url-loader?limit=10000&mimetype=application/font-woff" },
    { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      exclude: path.join(__dirname, 'client/images'),
      loader: "file-loader" },

    // other SVG
    { test: /\.svg$/,
      loader: 'url-loader',
      query: { mimetype: "image/svg+xml" },
      include: path.join(__dirname, 'client/images')
    },

   ]
  }
};

这是我在应用程序中的使用方式:

And here's how I'm using it in the app:

export class Banner extends React.Component {
    render() {
        console.log(this.props.banners);
        // = '../images/banners/frontPageBanner.png'
        const bannerImg = this.props.image.backgroundImage;

        var bannerStyle = {
            background: 'url(' + bannerImg + ')',
            backgroundSize: this.props.image.backgroundSize,
            backgroundPosition: this.props.image.backgroundPosition,
        }

        return (
            <section key={this.props.key} className="container hero" style={bannerStyle}>
                <div className="textbox">
                    <h2>{this.props.title}</h2>
                </div>
            </section>
        )
    }
}

这里是html:

<section class="container hero" style="background: url('../images/banners/frontPageBanner2.png') 100% 100% / contain;">
    ...
</section>

,但不显示图像.同样打开图像src链接仅显示一个空白屏幕.为什么?我该如何解决?

but no image is displayed. Also opening the image src link shows just a blank screen. Why? And how can i fix it?

您应该传递一个需要图像的var,当您使用webpack要求它时,它将生成一个base64内嵌图像,而不是相对的路径.

You should pass a var that is the result of requiring the image, when you require it using webpack, it'll generate a base64 inline image, not a relative path.

var DuckImage = require('./Duck.jpg');

var bannerStyle = {
    backgroundImage: 'url(' + DuckImage + ')',
    backgroundSize: this.props.image.backgroundSize,
    backgroundPosition: this.props.image.backgroundPosition,
}