0

I am trying to create react project form the scratch using webpack. Everything looks fine except the image. Seem images not loading, I can see src="Obeject Object". I used the same file-loader and url-loader on the below webpack but neithrt helps me to fix this issue. I might have missed something in the config file.

var webpack = require('webpack');
var path = require('path');
var nodeModulesPath = path.resolve(__dirname, 'node_modules');
var buildPath = path.resolve(__dirname, 'public', 'build');
var assetsPath = path.resolve(__dirname, 'src/app/assets');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var config = {

    devtool: 'eval-source-map',
    devServer: {
        historyApiFallback: true
    },
    entry: {
        index: ['babel-polyfill', './src/app/index.js']
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'index_bundle.js',
        publicPath: '/'
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                use: 'babel-loader',
                exclude: nodeModulesPath
            },

            {
                test: /\.(png|jpe?g|gif)$/i,
                loader: 'file-loader',
                options: {
                  publicPath: assetsPath,
                },
            },
            {
                test: /\.s[ac]ss$/i,
                include: [
                    nodeModulesPath,
                    path.resolve(__dirname, './src'),
                ],
                use: [
                    // Creates `style` nodes from JS strings
                    'style-loader',
                    // Translates CSS into CommonJS
                    'css-loader',
                    // Compiles Sass to CSS
                    'sass-loader',
                ],
            },
        ],
    },

    plugins: [
        new HtmlWebpackPlugin({
            template: './src/app/index.html'
        })
    ],
    devServer: {
        host: '0.0.0.0',//your ip address
        port: 3000,
        historyApiFallback: true,
        contentBase: './',
        hot: true
    },
    target: 'web'
};

module.exports = config;

I used image tag like below in react component.

<img src={require('./../assets/images/logo.png')} />

James Z
  • 12,209
  • 10
  • 24
  • 44
Sivaprakash D
  • 318
  • 1
  • 4
  • 17

1 Answers1

0

Have you tried using your image in your component like:

import Image from './image.jpg';

<img src={Image}/>

See: Referencing a local image in react

andrralv
  • 810
  • 7
  • 18
  • Yah and working. Ideally this is not perfect solution if suppose to be used more images .. – Sivaprakash D Apr 28 '20 at 03:07
  • Then what you are looking for is dynamic import (ES7): https://stackoverflow.com/questions/35914712/es6-conditional-dynamic-import-statements – andrralv Apr 29 '20 at 20:27