I'm fairly new to webpack but having some problems with css-loader or file-loader.
I'm trying to load a background-image but it doesn't work quite right. The background-image isn't shown, even though the devtools show the background-image
style.
If I copy the background-image
style to the element.style
block, everything works fine. Am I making a stupid mistake somewhere?
The body tag should have a background image. The style appears in the developer tools and there are no errors:
I can load the file 5a09e4424f2ccffb6a33915700f5cb12.jpg
, but the body has no background.
If I manually copy and paste css line to element.style
in the DevTools, everything works:
This happens if I bundle using webpack-dev-server
or just webpack
and in both Chrome and Firefox.
Other styles, such as body { background-color: red }
work fine.
This is the webpack.config.js:
const path = require('path');
module.exports = {
"entry": [
'./src/index.js'
],
"output": {
"path": path.join(__dirname, 'build'),
"filename": "bundle.js"
},
devtool: "source-map",
"module": {
"loaders": [
{
"test": /\.scss$/,
"loaders": ["style", "css?sourceMap", "sass?sourceMap"]
},
{
test: /\.jpg$/,
loader: "file-loader"
}
]
},
devServer: {
contentBase: './build'
}
};
After struggling with this problem for a day, I finally figured out how to rewrite urls within css using postcss
webpack.config.js
postcss.config.js
Where is your publicPath entry in output? eg:
publicPath: 'http://localhost:5000/', // absolute path req here for images in css to work with sourcemaps on. Must be actual numeric ip to access on lan.
https://github.com/webpack/docs/wiki/configuration#outputpublicpath
Please try using, for example:
css-loader in webpack:
Result in bundle.css is:
You can also try using the
~
in front of your files so that the webpack falls back to the loadersrequire
to resolve the url.It seems like browsers aren't fond of relative paths to background images on the body tag. (see also CSS Background image not loading and css background-image not working properly)
Changing the code slightly seemed to do the trick:
background-image: url(http://localhost:8080/5a09e4424f2ccffb6a33915700f5cb12.jpg)
. This is hardly ideal.Neither of these solve the real question, but do get you unstuck.
Webpack generates the css and
<link>
s them viablob:
urls, which seems to cause issues with loading background images.Development workaround
Inline the images via the file-loader in development (creates large base64 string in the css)
But allows for hot-reloading.
Production workaround
Use the ExtractTextPlugin to serve the css as normal file.