【问题标题】:React & Webpack: Loading and displaying images as background-imageReact & Webpack:加载和显示图像作为背景图像
【发布时间】:2016-05-23 09:06:47
【问题描述】:

我正在创建一个类似横幅的组件,其中图像设置为组件的背景,但我无法让它工作。我尝试了网上发布的不同建议,但没有成功,目前我不确定我的错误是在反应代码中还是 webpack 没有正确加载文件。

这是我的文件结构:

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

这是我的 webpack 配置:

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')
    },

   ]
  }
};

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

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 链接也只显示一个空白屏幕。为什么?我该如何解决?

【问题讨论】:

    标签: image reactjs webpack


    【解决方案1】:

    你应该传递一个 var 是需要图像的结果,当你使用 webpack 需要它时,它会生成一个 base64 内联图像,而不是相对路径。

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

    【讨论】:

    • 我已经尝试过了,是的,如果我手动将路径插入require() 它可以工作。但是,组件应该是动态的,并且 URL 必须从 props 中读取。 require(this.props.image.backgroundImage) 不起作用...
    • 您始终可以加载图像并传递给道具,但如果 URL 确实是动态的并且不应该捆绑在您的应用中,您肯定需要传递绝对路径 - 'localhost/myapp/public/img/myimage.jpg ' 例如。然后你就不需要使用 require 并且你的应用会更小。
    • 这就是我最终所做的,我使用绝对路径将来自同一服务器的照片作为带有 URL 的 JSON 数据提供。感谢您的帮助!
    猜你喜欢
    • 2016-11-12
    • 2016-11-25
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    相关资源
    最近更新 更多