2016-04-22 42 views
1

我正在與一個反應和webpack項目。我爲圖像使用了url loader插件。如果我想將圖像包含在img標籤中,這工作正常。但我想在我的CSS中包含一個圖像作爲背景圖像。即在css中使用webpack的圖像url /路徑?

const hero = require('../../images/landing-hero.jpg'); 

這將返回一個文件名,它在任何地方都能正常工作,除了我的css。

.hero { 
    background-image: url('3b1425242c422b429f78f272b0a4c0f7.jpg'); 
    background-size: cover; 
    position: relative; 
    display: block; 
    min-height: 101vh; 
    color: white; 
} 

我已經嘗試了一些沒有成功的路徑變體。但是做http://localhost:8080/3b1425242c422b429f78f272b0a4c0f7.jpg的作品。如何在不執行整個網址的情況下將圖片用作背景網址? 這是我的WebPack配置

'use strict'; 

/*=============================================>>>>> 
= MODULES = 
===============================================>>>>>*/ 

const path = require('path'); 
const webpack = require('webpack'); 
const WebpackNotifier = require('webpack-notifier'); 
// PostCSS 
const autoprefixer = require('autoprefixer'); 

'use strict'; 

/*=============================================>>>>> 
= MODULES = 
===============================================>>>>>*/ 

const path = require('path'); 
const webpack = require('webpack'); 
const WebpackNotifier = require('webpack-notifier'); 
// PostCSS 
const autoprefixer = require('autoprefixer'); 

/*= End of MODULES =*/ 
/*=============================================<<<<<*/ 

/*=============================================>>>>> 
= WEBPACK CONFIG = 
===============================================>>>>>*/ 

module.exports = { 
    entry: { 
    app: path.resolve(`${__dirname}/src/client/public/app/main.tsx`) 
    }, 
    output: { 
    path:  path.resolve(`${__dirname}/build/client`), 
    filename: 'public/zip/[name].bundle.js' 
    }, 
    module: { 
    loaders: [ 
     { test: /\.tsx$/, loader: 'babel!ts' }, 
     { test: /\.scss$/, loader: 'style!css?sourceMap!postcss!sass?sourceMap' }, 
     { test: /\.css$/, loader: 'style!css?sourceMap!postcss'}, 
     { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'} 
    ] 
    }, 
    postcss: function() { 
    return [ autoprefixer ]; 
    }, 
    ts: { 
    silent: true 
    }, 
    plugins: [ 
    new WebpackNotifier({ title: 'Webpack', alwaysNotify: true }), 
    new webpack.optimize.OccurenceOrderPlugin(), 
    ] 
}; 

/*= End of WEBPACK CONFIG =*/ 
/*=============================================<<<<<*/ 

我試着解決方案提供here與決心,網址加載器,但我不認爲我把決心,網址在我的裝載機合適的地方,因爲我的是略不同於他們的。新的webpack和我已經看過其他類似的問題,沒有運氣,所以很抱歉,如果這感覺像它的問題

+1

也許使用文件加載器而不是url加載器?根據https://github.com/webpack/css-loader,一切都應該開箱即用。 –

回答

3

根據this issue,當sourcemap啓用時,它會使用blob來爲您的頁面上的css 。這將導致問題,因爲背景url()是相對於CSS,因此在BLOB它找不到該文件,因此不呈現圖像。

它來解決此問題幾個方面:

  1. 使用DataUrl,看到url-loader,設置相應limit
  2. 如果圖像文件是大,你不希望使用數據網址,您可以將output.publicPath設置爲您的網址。例如通常在本地開發模式下,http://localhost:3000/。但是,這種解決方法並不完美,尤其是當您使用HTTPS時。你仍然可以寫一些簡單的代碼來相應地調整這個值。