Ok, so I've been reading article after article after article and have not found a good solution to this, what should be a very simple process in developing a web app...
I have my setup for webpack, babel, react and in my react app, I have a very basic css import. I've imported the image, which lives in src/static/assets/images/bg.png and I can embed it using inline css in my react component without troubles. However, I want to include my image from an included css file. The css file is parsed, but then I get the error 'Module build failed' and Can't resolve './bg.png' or a very similar path error when I mess around with the path inside the included css. I have file-loader, and url-loader installed and the file is moved into the dist/ folder route (though honestly, I would rather have an images/ folder in the dist where this goes, but that's another task.
So the quest: what needs to change to have the image included from the css. I've read https://create-react-app.dev/docs/adding-images-fonts-and-files/ and that alludes that my code should work, yet it doesn't.
Code is below, or from my repo if you want the whole code base: https://github.com/abendago/reactimages
REACT Code
import React from "react";
import './css/style.css'
import bg from './static/assets/images/bg.png'
function App() {
return (
<h1 style={{backgroundImage: "url(" + bg + ")"}}>In THe App Here</h1>
);
}
export default App;
src/css/style.css
body { background-image: url(./bg.png)}
webpack config
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
module.exports = {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader"
}
]
},
{
test: /\.css$/i,
use: [MiniCssExtractPlugin.loader, 'css-loader'],
},
{
test: /\.(png|jpg|gif)$/i,
use: [
{
loader: 'url-loader',
},
],
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin()
],
devServer: {
contentBase: path.join(__dirname, 'public')
}
};