htmlcssreactjswebpack

React/Webpack images not loading, but CSS does


So I just want to use some images in my React application, but images are not loading up. Some images are set up in CSS like that:

background-image: url('/../img/logo.png'); 

Another way I would like to use images in inside React components with img tag, how would I go about doing this?

Here is my webpack config:

const path = require('path');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = (env) => {
  const isProduction = env === 'production';
  return {
    entry: './src/app.js',
    output: {
      path: path.resolve(__dirname, 'public', 'dist'),
      filename: 'bundle.js'
    },
    module: {
      rules: [{
        loader: 'babel-loader',
        test: /\.js$/,
        exclude: /node_modules/
      }, {
        test: /\.s?css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              // you can specify a publicPath here
              // by default it use publicPath in webpackOptions.output
              publicPath: '../'
            }
          },
          {
            loader: 'css-loader',
            options: {
              sourceMap: true
            }
          },
          {
            loader: 'sass-loader',
            options: {
              sourceMap: true
            }
          }
        ]
      }]
    },
    plugins: [
      new MiniCssExtractPlugin({
      // Options similar to the same options in webpackOptions.output
      // both options are optional
      filename: "styles.css",
    })
    ],
    devtool: isProduction ? 'source-map' : 'inline-source-map',
    devServer: {
      contentBase: path.resolve(__dirname, 'public'),
      historyApiFallback: true,
      publicPath: '/dist/'
    },
    performance: {
      hints: process.env.NODE_ENV === 'production' ? "warning" : false
    },
  }
};

index.html inside public folder:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Kinnisvara ABC</title>
    <link rel="stylesheet" href="/dist/styles.css" type="text/css">
  </head>
  <body>
    <div id="app"></div>
    <script src="/dist/bundle.js"></script>
  </body>
</html>

CSS is loading up, but images are not.

Pictures of my file structure: enter image description here

enter image description here

enter image description here

Can anyone help me with that, please?


Solution

  • Have 2 way

    1. Use webpack url-loader Add this line to rules module in webpack file

      { test: /.(png|jpg|woff|woff2|eot|ttf|svg|gif)$/, loader: 'url-loader?limit=1024000' }

    2. Use serve to point image