Ben Gannaway Ben Gannaway - 1 month ago 25
CSS Question

Webpack inline CSS background images

I'm trying to get webpack to load images and can't seem to get it working. My configuration looks like this:

var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
publicPath: "/build/",
filename: 'bundle.js'
},
module: {
loaders: [
{
test: /\.jsx?/,
include: APP_DIR,
loader: 'babel'
},
{
test: /\.scss$/,
loaders: ["style", "css", "sass"]
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
},
{
test : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader : 'url-loader'
},
{
test: /\.(png|jpg|gif)$/,
loader: 'file-loader'
}
]
},
resolve: {
extensions: ['', '.js', '.jsx']
}
};


And I am trying to use as an inline CSS background image like this:

<div class="inner-panel"
style="background-image: url("/common/img/split-image/image.jpg");">
</div>


Also it doesn't work as an inline image:

<img src="/common/img/split-image/image.jpg">

Answer

Problem is with your image paths, not with your webpack config.

Try putting a ./ at the start of your path like so

"./common/img/split-image/image.jpg"

Other then that you should look at your file requires as well and make sure there are placing them where you want to place them.

Since you are using file-loader (and I think React as well), an example of how you would use it would be:

//CJS
var file = require("file!./file.png");
//ES6
import file from "file!./file.png";

//Later inside a React component
    const inStyle = {
        background-image: 'url(' + file + ')'
    }
    <div style={inStyle}/>

(React takes objects rather then strings for the style attribute)

url-loader should be the same. Hope this helps.