简体   繁体   中英

Including an image in imported css file in react using webpack

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')
  }
};

You have to set the relative path with your image to solve your issue since current your path doesn't relate to anything:

body { background-image: url('../static/assets/images/bg.png')}

You might want to install file loader and image-webpack-loader and update your webpack config to reflect the following.

{
        test: /\.(png|gif|jpe?g)$/,
        use: [
          'file-loader',
          {
            loader: 'image-webpack-loader',
            options: {
              mozjpege: {
                progressive: true,
                quality: 80,
              },
              optipng: {
                enabled: false,
              },
              pngquant:{
                 quality: '65-90',
                 speed: 4,
              },
            }
          }
        ]
      }

Although I think your image doesn't load when referenced in css, because you don't have a quote around it. Replace body { background-image: url(./bg.png)} with body { background-image: URL('./bg.png')} - https://developer.mozilla.org/en-US/docs/Web/CSS/background-image

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM