Reputation: 737
I'm trying to dynamically add an inline background-image url to a DOM element. The problem is that when inserted in the DOM, the image name isn't hashed and thus doesn't match the targeted image name.
For instance, here is the object I'm trying to use:
var project = {
title: "Foobar",
image: "../img/foobar.jpg"
};
And here is what javascript create in the DOM:
<div style="background-image: url(../img/foobar.jpg)"></div>
...when I would actually need something like:
<div style="background-image: url(2faf750010d2109a74e1ce1d02.jpg)"></div>
Here is my webpack.config.js
const path = require("path");
let config = {
mode: "development",
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "./app"),
filename: "./bundle.js"
},
watch: true,
module: {
rules: [
{
test: /\.s?css$/,
use: [
{ loader: "style-loader" },
{ loader: "css-loader" },
{ loader: "sass-loader" }
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
{
test: /\.(woff|woff2|eot|ttf|otf|svg)$/,
loader: 'file-loader'
}
]
}
}
module.exports = config;
It actually works if I simply add a class name with JavaScript and manage the background-image with CSS, since CSS paths are properly hashed, but it's not quite I need at the moment :/
Thanks for any help!
Upvotes: 0
Views: 41
Reputation: 168966
To get the Webpack asset URL instead of the original source with file-loader
, require
it:
var project = {
title: "Foobar",
image: require("../img/foobar.jpg"),
};
Upvotes: 4