Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to load background image from Css file Webpack5

I’m trying to put an image as background in a div but it doesn’t recognize it because webpack changes the path to http://localhost:8080/gaia.png instead of http://localhost:8080/assets/images/gaia.png
The image is displayed correctly inside an tag but it doesn’t load if I want to use it from the Css file.
I’m sure the problem is the file path but I don’t know how to fix it.
enter image description here

enter image description here

index.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import './assets/style/style.css'
import './assets/images/gaia.png'
import './assets/fonts/CascadiaCode.ttf'

const fun = () => {
  console.log('hey')
}
fun();

webpack.config.js

const HtmlWebpackPlugin = require("html-webpack-plugin");
const path = require('path');

module.exports = {
  mode: 'development',
  devtool: 'inline-source-map',
  entry: './src/index.js',
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, 'src', 'index.html')
    })
  ],
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
        generator: {
          filename: '[name][ext][query]',
          outputPath: 'assets/images/',
        },
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
        generator: {
          filename: '[name][ext][query]',
          outputPath: 'assets/fonts/',
        },
      },
    ],
  },
};

style.css

.container {
  width: 300px;
  height: 300px;
  background-image: url("../images/gaia.png");
  background-size: auto;
}

>Solution :

delete outputpath and set it up as :

generator: {
         filename: 'assets/images/[hash][ext][query]'
       }
     }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading