2017-03-04 164 views
0

在這種情況下,我試圖設置排序的高階組件,並進一步實現它的「動態」圖像加載。你能解釋一下爲了引用組件內部而做錯了什麼嗎?Webpack&React。加載的圖像無法解析路徑404

陣營元器件

class Slide extends Component { 
    constructor(props) { 
    super(props) 
    } 

    render() { 

    let imageLeft = { 
    backgroundImage: 'url(./assets/introleft.png)' 
    } 

    return (
     <div className={styles.someStyles}> 
     <div className={styles.someStyles} style={imageLeft} >&nbsp;</div> 
     </div> 
    ) 
    } 

} 

... state 

export default connect(mapStateToProps)(Slide); 

項目結構

enter image description here

的WebPack配置

const path = require('path'), 
     webpack = require('webpack'), 
     HtmlWebpackPlugin = require('html-webpack-plugin'); 

module.exports = { 
    entry: [ 
    'react-hot-loader/patch', 
    'webpack-dev-server/client?http://localhost:8080', 
    'webpack/hot/only-dev-server', 
    './index.js' 
    ], 
    output: { 
    filename: 'bundle.js', 
    path: path.resolve(__dirname, 'build'), 
    publicPath: '/' 
    }, 
    context: path.resolve(__dirname, 'logic'), 
    devtool: 'inline-source-map',  
    devServer: { 
    hot: true, 
    contentBase: path.resolve(__dirname, 'build'), 
    publicPath: '/' 
    }, 

    module: { 
    rules: [ 
     { 
     test: /\.js$/, 
     use: [ 
      'babel-loader', 
     ], 
     exclude: /node_modules/ 
     }, 
     { 
     test: /\.css$/, 
     use: [ 
      'style-loader', 
      'css-loader?modules', 
      'postcss-loader', 
     ], 
     },{ 
     test: /\.png$/, 
     use: { loader: 'url-loader', options: { limit: 15000 } }, 
     }, 
     { 
     test: /\.svg$/, 
     use: { 
      loader: 'svg-url-loader', 
      options: {} 
     } 
    ], 
    }, 

    plugins: [ 
    new webpack.HotModuleReplacementPlugin(), 
    new webpack.NamedModulesPlugin(), 
    new HtmlWebpackPlugin({ 
     template: './index.template.html' 
    })<script> tag 
    ], 
}; 

P.S:項目沒有node.js服務器,只是wepback-dev。所以react-router使用哈希歷史記錄/#,如果它影響webpackpublicPath屬性。

回答

1

當您使用backgroundImage: 'url(./assets/introleft.png)'時,它將按原樣插入(它只是一個字符串),因此您的url-loader將不會應用於它。相反,你應該導入圖像:

import introleft from './assets/introleft.png'; 

的WebPack將已經應用了url-loader和你回來無論是傳輸數據的URL或URL所提取的圖像,如果尺寸過大。您現在需要做的就是將該URL放入您的backgroundImage

backgroundImage: `url(${introleft})`